简体   繁体   English

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

[英]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的类型loginDateIO Day但是这样我将无法派生EqShow ,因此在使用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.

相关问题 如何仅禁用日期选择日期中当前日期之后的1天 - how to disable only 1 day after current date in datepicker date 仅显示每天的最新日期记录 - show only latest date record for each day 如何在GoogleAppEngine应用中的Java中获取当前日期,以及如何从该日期中分离出Day,Month和Year并将其存储在数据存储区中 - how to get current date in java in GoogleAppEngine app, and separate Day, Month and Year from that date and store it in datastore 将Date类型的当前日期与Oracle中的Varchar日期列进行比较 - comparing current day of Date type with Varchar day column in Oracle 如何每天将日志文件存储在目录(具有当前日期的目录名称)中 - how to store log files in directory (directory name having current date) every day 如何比较记录日期和当前日期? - How to compare a record date with current date? 如何在Codeigniter的当前日期中插入日期间隔? - How to insert day interval in current date in codeigniter? 带有强制年份和月份以及仅可选日期的记录日期的最佳方法 - Best way to record date with mandatory year and month, and only optional day 仅提取日期的天数并与当前的天数进行比较 - Extract only the number of the day of the date and compare it with the current one 将日期添加到当前日期 - add day to current date
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM