简体   繁体   English

Haskell:文件访问时间格式化“yyyy-MM-dd”

[英]Haskell: File Access Time Formatted “yyyy-MM-dd”

I'm getting quite lost in all the different date and time libraries available to me in Haskell. 我在Haskell中可用的所有不同日期和时间库中都迷失了。 What I'm trying to do is format the file modification time as "yyyy-MM-dd". 我要做的是将文件修改时间格式化为“yyyy-MM-dd”。 Can someone show me how to do that? 有人可以告诉我该怎么做吗?

I've got this code-snippet: 我有这个代码片段:

main = do
  times <- mapM getModificationTime $ dataFiles config -- dataFiles returns [FilePath].
  -- I'd like to do something like the following:
  (putStr . unlines . map formatDate) times

This is what I've attempted. 这就是我的尝试。 Please don't laugh! 请不要笑!

formatDate t =
  let (year, month, day) = toGregorian $ utctDay t
   in intercalate "-" $ map show [year, fromIntegral month, fromIntegral day]

I know it's not completely up to my specifications yet, because I won't get months and days left-filled with zero. 我知道这还不完全取决于我的规格,因为我不会在几个月和几天内留下零。 I can fix that. 我可以解决这个问题。 But I figure there's a more elegant way to get what I'm after, which is why I've titled my post with what I'm after rather than the current error I'm getting, which, for the sake of completeness is Couldn't match expected type 'UTCTime' with actual type 'ClockTime' . 但我想有一个更优雅的方式来获得我后,这就是为什么我题为什么我之后,而不是当前的错误我得到,其中,对完整性的考虑是为我的后Couldn't match expected type 'UTCTime' with actual type 'ClockTime'

Thanks for whatever help you can give or clarity you can provide. 感谢您提供的任何帮助或您可以提供的清晰度。

Here's one approach: 这是一种方法:

λ> :m + Data.Time
λ> :m + System.Locale
λ> t <- getModificationTime "amy.hs"
λ> formatTime defaultTimeLocale "%Y-%m-%d" t
"2013-05-14"

You'll need the old-locale package. 你需要old-locale包。 Despite the name, that is the current one as far as I know. 尽管有这个名字,据我所知,这是现在的名字。 There is no new-locale or locale ! 没有new-localelocale

Something like this should convert the ClockTime into a UTCTime : 这样的事情应该将ClockTime转换为UTCTime

import System.Time
import Data.Time.Clock.POSIX

utcTimeFromClockTime :: ClockTime -> UTCTime
utcTimeFromClockTime (TOD seconds picoseconds)
   = posixSecondsToUTCTime . fromRational
        $ fromInteger seconds + fromInteger picoseconds / 1000000000000

You probably want to convert that to use your local time zone. 您可能希望将其转换为使用您当地的时区。 Use utcToLocalZonedTime :: UTCTime -> IO ZonedTime from Data.Time.LocalTime. 使用utcToLocalZonedTime :: UTCTime -> IO ZonedTime ZonedTime。

Either way, you then have a timestamp you can format: 无论哪种方式,您都有一个可以格式化的时间戳:

import Data.Time.Format
import System.Locale

formatIsoDate :: FormatTime t => t -> String
formatIsoDate = formatTime defaultTimeLocale "%F"

(Sorry, I've not tested any of this code.) (对不起,我没有测试过这些代码。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM