【问题标题】:SimpleDateFormat does not parse correctlySimpleDateFormat 无法正确解析
【发布时间】:2021-09-10 20:34:01
【问题描述】:
  String current = "07:00:00.160"

  DateFormat df2 = new SimpleDateFormat("HH:mm:ss.SSS"); 

  DateList.add(df2.parse(current));

返回 [Thu Jan 01 07:00:00 GMT 1970]

我也试过了

    Date currentdate;
    currentdate = df2.parse(current);
    df2.format(currentdate);
    DateList.add(currentdate);

返回也

[1970 年 1 月 1 日星期四 07:00:00 GMT]

我也尝试过使用df2.setLenient(false);

【问题讨论】:

  • 我建议你不要使用SimpleDateFormatDate。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time APILocalTime
  • 您报告的结果是我预期的结果。你期待什么结果?
  • 看起来正确。有什么问题?
  • java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用它们并切换到modern Date-Time API。我强烈建议您使用solution by Ole V.V.

标签: java simpledateformat datetime-parsing timeofday


【解决方案1】:

java.time.LocalTime

我建议您使用现代 Java 日期和时间 API java.time 来处理您的时间工作。用于一天中时间的类是LocalTime

我们甚至不需要指定格式化程序来解析您的字符串,因为它是一天中某个时间的默认格式(也在 ISO 8601 标准中规定)。

    String current = "07:00:00.160";
    LocalTime time = LocalTime.parse(current);
    System.out.println(time);

输出:

07:00:00.160

链接

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    相关资源
    最近更新 更多