在 Haskell 中获取当前年/月/日
问题:
使用 haskell,你想获取 UTC 时区的当前年、月和日作为整数值。
解决方案
你需要 time 包来完成此任务。使用 cabal install time 安装。
我们的代码类似于此 HaskellWiki 条目,但它提供了一个独立的可运行程序(使用 runghc <文件名>.hs 执行),对初学者来说更易读。
UTC 时间:
注意 UTC 时间可能根据你的时区与你的本地时间不同。
get_current_date.hs
import Data.Time.Clock
import Data.Time.Calendar
main = do
now <- getCurrentTime
let (year, month, day) = toGregorian $ utctDay now
putStrLn $ "Year: " ++ show year
putStrLn $ "Month: " ++ show month
putStrLn $ "Day: " ++ show day本地时间:
也可以使用系统默认时区获取当前本地时间:
get_current_local_date.hs
import Data.Time.Clock
import Data.Time.Calendar
import Data.Time.LocalTime
main = do
now <- getCurrentTime
timezone <- getCurrentTimeZone
let zoneNow = utcToLocalTime timezone now
let (year, month, day) = toGregorian $ localDay zoneNow
putStrLn $ "Year: " ++ show year
putStrLn $ "Month: " ++ show month
putStrLn $ "Day: " ++ show day使用此方法也会考虑夏令时。
Check out similar posts by category:
Haskell
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow