我正在查看time模块,我想要这样的东西:
import Data.Time.LocalTime
timeOfDayAndDayOfWeek :: ZonedTime -> (TimeOfDay, DayOfWeek)
我该怎么做?
答案 0 :(得分:1)
这对你有用吗?
import Data.Time.LocalTime
(ZonedTime, TimeOfDay, getZonedTime, localDay, localTimeOfDay,
zonedTimeToLocalTime)
import Data.Time.Calendar.WeekDate (toWeekDate)
-- toWeekDate numbers the days 1 for Monday to 7 for Sunday.
data DayOfWeek = Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday
deriving (Eq, Read, Show)
instance Enum DayOfWeek where
toEnum 0 = Sunday
toEnum 1 = Monday
toEnum 2 = Tuesday
toEnum 3 = Wednesday
toEnum 4 = Thursday
toEnum 5 = Friday
toEnum 6 = Saturday
toEnum 7 = Sunday -- Yes, twice.
toEnum n = toEnum (n `mod` 7)
fromEnum Monday = 1
fromEnum Tuesday = 2
fromEnum Wednesday = 3
fromEnum Thursday = 4
fromEnum Friday = 5
fromEnum Saturday = 6
fromEnum Sunday = 7
timeOfDayAndDayOfWeek :: ZonedTime -> (TimeOfDay, DayOfWeek)
timeOfDayAndDayOfWeek zt = let
lt = zonedTimeToLocalTime zt
day = localDay lt
(_, _, weekDayNumber) = toWeekDate day
dow = toEnum weekDayNumber
tod = localTimeOfDay lt
in
(tod, dow)
main :: IO ()
main = do
zt <- getZonedTime
let (tod, dow) = timeOfDayAndDayOfWeek zt
print tod
print dow
您可能更喜欢这个版本的包装函数而不是样板,由4castle建议。 (特别是如果你必须使用从整数到Enum
的多个映射。)
import Data.Time.LocalTime
(ZonedTime, TimeOfDay, getZonedTime, localDay, localTimeOfDay,
zonedTimeToLocalTime)
import Data.Time.Calendar.WeekDate (toWeekDate)
data DayOfWeek = Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday
deriving (Enum, Eq, Read, Show)
-- toWeekDate numbers the days 1 for Monday to 7 for Sunday.
weekDateToDayOfWeek :: (Integer, Int, Int) -> DayOfWeek
weekDateToDayOfWeek (_, _, d) = toEnum (d-1)
timeOfDayAndDayOfWeek :: ZonedTime -> (TimeOfDay, DayOfWeek)
timeOfDayAndDayOfWeek zt = let
lt = zonedTimeToLocalTime zt
dow = (weekDateToDayOfWeek . toWeekDate . localDay) lt
tod = localTimeOfDay lt
in
(tod, dow)
main :: IO ()
main = do
zt <- getZonedTime
let (tod, dow) = timeOfDayAndDayOfWeek zt
print tod
print dow
答案 1 :(得分:1)
您可以从ZonedTime
到LocalTime
再到Day
。
通过Day
,您可以使用https://hackage.haskell.org/package/time-1.9.3/docs/Data-Time-Calendar.html#t:DayOfWeek来获取DayOfWeek
枚举。
并使用localTimeOfDay
从LocalTime
到TimeOfDay
。