【问题标题】:Convert String "22/08/2013" to date format 2013/08/22将字符串“22/08/2013”​​转换为日期格式 2013/08/22
【发布时间】:2013-08-29 05:31:51
【问题描述】:

这是我在 scala 中的代码

 var s:String ="22/08/2013"
 var  simpleDateFormat:SimpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
 var  date:Date = simpleDateFormat.parse(s);
 println(date)

日期不变。 日期与 22/08/2013 相同的格式 2013/08/22 没有变化

如何在scala中将格式dd/mm/yyyy更改为yyyy/mm/dd

【问题讨论】:

  • scala 代码中最好省略分号。这是首选的风格。也不需要指定像 String 这样的常见类型。
  • @Vishal 好的,vishal 这是我的错误……感谢您的回答
  • 你可能想看看日期格式化教程..docs.oracle.com/javase/tutorial/i18n/format/…
  • @Shrey thans 这对我很有帮助
  • 现代评论:我建议你不要使用SimpleDateFormat和Date。这些类设计不佳且早已过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time API 的LocalDate 和DateTimeFormatter。

标签: scala date date-format simpledateformat


【解决方案1】:

您需要定义一个SimpleDateFormat,它首先解析您的字符串并从中获取Date。然后将其转换为任何格式。

 var s:String ="22/08/2013"
 var  simpleDateFormat:SimpleDateFormat = new SimpleDateFormat("dd/mm/yyyy");
 var  date:Date = simpleDateFormat.parse(s);
 val ans = new SimpleDateFormat("yyyy/mm/dd").format(date) 
 println(ans)

【讨论】:

    【解决方案2】:

    我试过了,它对我有用。

    val s: String = "22/08/2013"
    val simpleDateFormat: SimpleDateFormat = new SimpleDateFormat("dd/mm/yyyy")
    val date = simpleDateFormat.parse(s)
    val df = new SimpleDateFormat("yyyy/mm/dd")
    println(df.format(date))
    

    【讨论】:

    • 我需要 df 作为 util date 怎么做,.,
    • 抱歉,我不知道可以在格式之间转换的标准实用程序函数。将不得不编写自定义帮助函数。
    • @zzztimbo 你为什么这么认为。如果你看到回答的时间,我们都回答了 1 分钟的差异。我也没有复制粘贴其他答案。如果你仔细观察,我遵循了使用vals 而不是vars 的Scala 约定
    • @user007 抱歉,我没有注意到 vals。使用 vars 是荒谬的。
    【解决方案3】:

    John Vishal 的回答中有一个细微的错误: mm 将 08 定义为分钟,而不是月份。请改用 MM。

    更正的代码:

    val s = "2013_08_14"
    val simpleDateFormat: SimpleDateFormat = new SimpleDateFormat("yyyy_MM_dd")
    val date = simpleDateFormat.parse(s)
    val df = new SimpleDateFormat("dd-MMM-yyyy")
    println(df.format(date))
    

    【讨论】:

    • 正确,即使其他两个答案都有这个错误。不过,我们不应该在SimpleDateFormat 上浪费时间。这是一个出了名的麻烦和过时的课程。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2015-01-14
    • 2016-06-22
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多