如何仅将记录中的当前日期存储为 Day 类型?

How to store current date in a record as a Day type only?

如何在记录中将当前日期存储为 Day 类型?这是正确的做法吗?我想这样做是为了能够在应用程序中操作日期,而且还可以使用 Opaleye 或 Esqueleto 将它们存储在数据库中。

我有这个:

import Data.Time
import Data.Time.Format

data User = User
  { userId    :: Int
  , name      :: Text
  , loginDate :: Day
  } deriving (Eq, Show)


currentDay :: Day
currentDay = utctDay <$> getCurrentTime ???

users :: [User]
users = [ User 1 "A" currentDay
        , User 2 "B" currentDay
        ]

但是currentDay的类型是IO Day。我如何才能将其作为 Day 获取?我猜想如果不破坏类型安全是不可能的,但我不确定。

我可以将 loginDate 的类型更改为 IO Day,但那样我就无法派生出 EqShow,因此无法使用 deriveJSON 在使用 Servant 时。如果我将 currentDay 的类型更改为 IO Day,将 users 的类型更改为 IO [User],那么我将无法使用 Servant 类型。

currentDay(以及 getCurrentTime)是一个 IO 操作。您必须在 IO-monad 中执行它以检索当前日期。

您的代码应如下所示:

currentDay :: IO Day
currentDay = utctDay <$> getCurrentTime

createUsers :: IO [User]
createUsers = do
  today <- currentDay
  return [ User 1 "A" today, User 2 "B" today ]