You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haskell如何获取ISO8601格式的当前时间字符串?

在Haskell中获取ISO8601格式的当前时间字符串

不需要依赖废弃的old-locale包,用最新版的time包(>=1.9)就能直接实现,以下是完整的可调用IO动作:

代码实现

首先导入必要的模块:

import Data.Time.Clock (getCurrentTime)
import Data.Time.Format (formatTime, defaultTimeLocale)

定义获取ISO8601格式时间的函数:

-- 基础ISO8601格式(不含毫秒)
getCurrentISO8601 :: IO String
getCurrentISO8601 = formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S%z" <$> getCurrentTime

-- 带毫秒的ISO8601格式
getCurrentISO8601WithMillis :: IO String
getCurrentISO8601WithMillis = formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S.%3Q%z" <$> getCurrentTime

说明

  • 现在defaultTimeLocale已经整合到Data.Time.Format模块中,无需再导入废弃的System.Locale,也不用安装old-locale包,彻底避免版本兼容问题。
  • 格式字符串说明:
    • %Y-%m-%d:年-月-日
    • T:ISO8601要求的时间分隔符
    • %H:%M:%S:时:分:秒
    • %3Q:保留三位小数的毫秒(可选)
    • %z:时区偏移(如+0800表示东八区)

使用示例

在GHCi中直接调用:

ghci> getCurrentISO8601
"2024-05-20T15:12:34+0800"
ghci> getCurrentISO8601WithMillis
"2024-05-20T15:12:34.567+0800"

内容的提问来源于stack exchange,提问作者beyarkay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:26:02