【问题标题】:How to convert the dd/mm/yyyy to yyyymmdd in scala by using joda time如何使用 joda time 在 scala 中将 dd/mm/yyyy 转换为 yyyymmdd
【发布时间】:2018-04-16 15:27:34
【问题描述】:

如何将 dd/mm/yyyy 转换为 yyyymmdd 格式以及 在 Scala 中使用 joda timedd/m/yyyy 转换为 yyyymmdd 格式。

我正在使用这个依赖项

 "joda-time" % "joda-time" % "2.9.9",

【问题讨论】:

  • 有什么理由不使用java.time

标签: scala jodatime


【解决方案1】:

This answer 已经用 Java 回答了你的问题,但在这里它被翻译成 Scala:

import org.joda.time.DateTime
import org.joda.time.format.{DateTimeFormat, DateTimeFormatter}

// define original date format
val originalFormat: DateTimeFormatter = DateTimeFormat.forPattern("dd/MM/yyyy")
val input: DateTime = originalFormat.parseDateTime("02/09/2017")

// define new format
val newFormat: DateTimeFormatter = DateTimeFormat.forPattern("yyyyMMdd")
val output: String = newFormat.print(input) // 20170902

此代码已经说明了您日期中缺少前导 0 的原因(即,它会将 02/9/20172/9/2017 视为同一件事)。但它不会预测一年中的缺失部分,因此2/9/17 将输出为00170902 而不是20170902

正如我之前提到的答案,您可以使用 java.time 来做同样的事情:

import java.time.LocalDate
import java.time.format.DateTimeFormatter

val originalFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy")
val input = LocalDate.parse("02/09/2017", originalFormat)
val newFormat = DateTimeFormatter.ofPattern("yyyyMMdd")
val output = input.format(newFormat)

【讨论】:

    【解决方案2】:
    import org.joda.time.DateTime
    import org.joda.time.format._
    
    val fmt = DateTimeFormat.forPattern("dd/mm/yyyy")
    val dt = fmt.parseDateTime("02/02/2017")
    val fmt2 = DateTimeFormat.forPattern("yyyymmdd")
    fmt2.print(dt)
    

    【讨论】:

    • 模式错误!使用“MM”,而不是“mm”。
    • 我只是使用了我在问题上看到的相同模式。
    • 错误模式MM不是mm
    猜你喜欢
    • 2011-10-15
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多