【问题标题】:Working with DateTime in Play 2.3.7 framework在 Play 2.3.7 框架中使用 DateTime
【发布时间】:2014-12-12 23:00:55
【问题描述】:

我正在寻找在 Play 框架中使用 datetime 的干净解决方案。具体来说,我需要将日期时间保存在数据库中,将该日期时间转换为 Scala 对象,然后将该日期时间与 Json 相互转换。

例如,我正在做一个像 eBay 这样的竞价服务,所以我想保留一个项目的创建时间,以及竞价时间结束的时间。我有一个像这样的简单模型:

case class Item(name: String, description: String, start: DateTime, end: DateTime)

由于 Slick 不支持 Joda DateTime,我使用 MappedColumnType 在 java.sql.Timestamp 和 Joda DateTime 之间进行转换。这是微不足道的,但如果有更好的解决方案,我将不胜感激。

我之所以使用 Joda DateTime 而不是 java.sql.Timestamp 是因为 Play 现在确实知道如何将 Timestamp 写入 Json,而我在网上找到的所有解决方案都需要大量的补丁代码。

有了 Joda DateTime,我遇到了另一个问题。 Play 将 DateTime 写为 Long 数字,这很好,但首选完整格式的日期。问题是客户端只能提交日期时间为“yyyy-MM-dd”,没有时间和时区。

这是我目前的尝试:

 implicit val itemFormatter = (
    (__ \ "ean").format[Long] and
      (__ \ "description").format[String] and
      (__ \ "start").format[DateTime] and
      (__ \ "end").format[DateTime]
    )(Item.apply _, unlift(Item.unapply))

  val userDateFormatter = "dd/MM/yyyy HH:mm:ss"
  implicit val jodaDateTimeReads = Reads.jodaDateReads(userDateFormatter)
  implicit val jodaDateTimeWrites = Writes.jodaDateWrites(userDateFormatter)
  implicit val jodaDateTimeFormats = Format(jodaDateTimeReads, jodaDateTimeWrites)

尝试使用上述格式发布时间时收到的错误消息是:

error.expected.jodadate.format,WrappedArray(yyyy-MM-dd)

这在 Ruby/Rails 等其他语言/框架中似乎是一件微不足道的事情,但我觉得 Scala 严重缺乏日期和时间支持。

【问题讨论】:

  • 您的 userDateFormatter 仍然需要每小时格式。
  • 另外,这是自上而下执行的代码,因此当您创建 itemFormatter、在 itemFormatter 上方定义它们或使它们成为惰性 val 时,joda-fields 还没有被赋值!

标签: json scala datetime playframework-2.0


【解决方案1】:

我找到了一个简单的解决方案。基本上我必须覆盖 DateTime 的默认读取和写入,如下所示:

# If you use Timestamp
implicit val tsreads: Reads[Timestamp] = Reads.of[Long] map (new Timestamp(_))
implicit val tswrites: Writes[Timestamp] = Writes { (ts: Timestamp) => JsString(ts.toString)}

# If you use DateTime
implicit val tsreads: Reads[DateTime] = Reads.of[String] map (new DateTime(_))
implicit val tswrites: Writes[DateTime] = Writes { (dt: DateTime) => JsString(dt.toString)}

【讨论】:

  • 嗨@Khanetor 你把这个覆盖代码放在模型或控制器的哪里?
  • 最好在模型的伴随对象中。它可以在任何地方。
猜你喜欢
  • 1970-01-01
  • 2015-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多