[英]How to store current date in a record as a Day type only?
How can I store in a record the current date as a Day
type? 如何将当前日期存储为
Day
类型记录? Is this the correct way of doing it? 这是正确的做法吗? I want to do this to be able to manipulate dates in the application but also to store them in a database using Opaleye or Esqueleto.
我想这样做是为了能够在应用程序中操作日期,还可以使用Opaleye或Esqueleto将它们存储在数据库中。
I have this: 我有这个:
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
]
But the type of currentDay
is IO Day
. 但是
currentDay
的类型是IO Day
。 How can I get it as Day
only? 我如何才能仅将其作为
Day
? I am guessing that is not possible without breaking type safety but I am not sure. 我猜想如果不破坏类型安全性是不可能的,但是我不确定。
I could change the type of loginDate
to IO Day
but then I wouldn't be able to derive Eq
and Show
and thus be unable to use deriveJSON
while using Servant. 我可以将
loginDate
的类型loginDate
为IO Day
但是这样我将无法派生Eq
和Show
,因此在使用Servant时无法使用deriveJSON
。 If I change the type of currentDay
to IO Day
and users
to IO [User]
then I cannot use Servant types. 如果将
currentDay
的类型更改为IO Day
,将users
更改为IO [User]
则无法使用Servant类型。
currentDay
(as well as getCurrentTime
) is an IO-action. currentDay
(以及getCurrentTime
)是一个IO操作。 You have to execute it in the IO-monad to retrieve the current day. 你必须在IO-单子执行它来检索当前的一天。
You code should look like: 您的代码应如下所示:
currentDay :: IO Day
currentDay = utctDay <$> getCurrentTime
createUsers :: IO [User]
createUsers = do
today <- currentDay
return [ User 1 "A" today, User 2 "B" today ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.