Haskell 中的日期函式

黃志斌發表於2019-10-23

圖靈教育的程式設計日曆(其實是周曆)每週使用一種程式設計語言以“YYYY-MM-DD”格式輸出當天的日期。注意:這裡的當天是指程式執行時的日期,而不是程式設計日曆中的日期。10月份的第4周是 Haskell 語言:

但是,這個程式是有問題的:

根據給出的錯誤資訊,刪除 HackingDate.hs 的第2行就行了:

這個程式中用到的 getZonedTime, formatTime, defaultTimeLocale 等函式的資訊如下:

$ ghci
GHCi, version 8.6.5: http://www.haskell.org/ghc/  :? for help
Prelude> :info Data.Time.getZonedTime
time-1.8.0.2:Data.Time.LocalTime.Internal.ZonedTime.getZonedTime ::
  IO time-1.8.0.2:Data.Time.LocalTime.Internal.ZonedTime.ZonedTime
      -- Defined in ‘time-1.8.0.2:Data.Time.LocalTime.Internal.ZonedTime’
Prelude> :info Data.Time.formatTime
Data.Time.Format.formatTime ::
  Data.Time.Format.FormatTime t =>
  time-1.8.0.2:Data.Time.Format.Locale.TimeLocale
  -> String -> t -> String
      -- Defined in ‘Data.Time.Format’
Prelude> :info Data.Time.defaultTimeLocale
time-1.8.0.2:Data.Time.Format.Locale.defaultTimeLocale ::
  time-1.8.0.2:Data.Time.Format.Locale.TimeLocale
      -- Defined in ‘time-1.8.0.2:Data.Time.Format.Locale’

其中,getZonedTime 返回當前的時間(帶有時區資訊):

Prelude> a <- Data.Time.getZonedTime
Prelude> a
2019-10-23 19:55:23.247136385 CST

這裡的 CST 是 China Standard Time (UTC+8)。

Data.Time.defaultTimeLocale 的值:

Prelude> Data.Time.defaultTimeLocale
TimeLocale {wDays = [("Sunday","Sun"),("Monday","Mon"),("Tuesday","Tue"),("Wednesday","Wed"),("Thursday","Thu"),("Friday","Fri"),("Saturday","Sat")], months = [("January","Jan"),("February","Feb"),("March","Mar"),("April","Apr"),("May","May"),("June","Jun"),("July","Jul"),("August","Aug"),("September","Sep"),("October","Oct"),("November","Nov"),("December","Dec")], amPm = ("AM","PM"), dateTimeFmt = "%a %b %e %H:%M:%S %Z %Y", dateFmt = "%m/%d/%y", timeFmt = "%H:%M:%S", time12Fmt = "%I:%M:%S %p", knownTimeZones = [UT,GMT,EST,EDT,CST,CDT,MST,MDT,PST,PDT]}

這裡的 CST 是 Central Standard Time (UTC-6)。

System.Locale.defaultTimeLocale 的值略有不同(沒有時區相關的資訊):

Prelude> System.Locale.defaultTimeLocale
TimeLocale {wDays = [("Sunday","Sun"),("Monday","Mon"),("Tuesday","Tue"),("Wednesday","Wed"),("Thursday","Thu"),("Friday","Fri"),("Saturday","Sat")], months = [("January","Jan"),("February","Feb"),("March","Mar"),("April","Apr"),("May","May"),("June","Jun"),("July","Jul"),("August","Aug"),("September","Sep"),("October","Oct"),("November","Nov"),("December","Dec")], intervals = [("year","years"),("month","months"),("day","days"),("hour","hours"),("min","mins"),("sec","secs"),("usec","usecs")], amPm = ("AM","PM"), dateTimeFmt = "%a %b %e %H:%M:%S %Z %Y", dateFmt = "%m/%d/%y", timeFmt = "%H:%M:%S", time12Fmt = "%I:%M:%S %p"}

時區資訊

相關文章