且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

处理时间和日期的更简单方法?

更新时间:2023-11-28 21:33:16

固定为使用timezone-olson/timezone-series进行正确的时区处理.

Fixed to use timezone-olson / timezone-series for correct timezone processing.

您应该能够使用time软件包执行几乎所有操作,只是在Linux系统上正确的时区处理将需要timezone-olsontimezone-series软件包;我不确定如何在Windows系统上执行此操作.也许其他人有更好的方法.

You should be able to do almost everything with the time package, except that proper timezone processing will require timezone-olson and timezone-series packages on Linux systems; I'm not sure how to do it on Windows systems. Maybe someone else has a better way.

代码如下:

module Time where

import Data.Time                             -- package "time"
import Data.Time.Calendar.WeekDate           -- package "time"
import Data.Time.LocalTime.TimeZone.Olson    -- package "timezone-olson"
import Data.Time.LocalTime.TimeZone.Series   -- package "timezone-series"

-- |POSIX-specific timezone lookup
lookupTimeZone :: String -> IO TimeZoneSeries
lookupTimeZone tz =
  getTimeZoneSeriesFromOlsonFile ("/usr/share/zoneinfo/" ++ tz)

data MyTime = MyTime
  { year :: Integer
  , month :: Int
  , week :: Int
  , dayOfMonth :: Int
  , dayOfWeek :: Int
  , hour :: Int
  , minutes :: Int
  , seconds :: Int
  } deriving (Show)

getMyTime :: TimeZoneSeries -> UTCTime -> MyTime
getMyTime tz t =
  let LocalTime day (TimeOfDay hh mm ss) = utcToLocalTime' tz t
      (yr, mn, dom) = toGregorian day
      (_,  wk, dow) = toWeekDate day
  in MyTime yr mn wk dom dow hh mm (round ss)

main :: IO ()
main = do
  currentTime <- getCurrentTime
  -- Note: if you want time in local timezone, use:
  -- tz <- getTimeZoneSeriesFromOlsonFile "/etc/localtime"
  tz <- lookupTimeZone "Asia/Tokyo"
  print $ getMyTime tz currentTime

一些注意事项:

  • lookupTimeZone如果在/usr/share/zoneinfo/your/timezone
  • 找不到时区文件,将引发异常.
  • 如果用周"表示一年中的某周",则可能要查阅toWeekDate的文档,以准确了解其定义.
  • 如果要以字符串格式表示月份或天数,则可以使用Data.Time.Format中的函数(仍在time包中)以当前(或某些其他)语言环境格式化它们.
  • lookupTimeZone will throw an exception if it can't find the timezone file at /usr/share/zoneinfo/your/timezone
  • If by "week", you meant "week of the year", you may want to consult the documentation for toWeekDate to see exactly how that's defined.
  • If you want months or days in string format, you can use the functions in Data.Time.Format (still in the time package) to format them in the current (or some other) locale.