DateTimeFormatter比SimpleDateFormat更严格吗?解析日期(以毫秒为单位) [英] Is DateTimeFormatter more strict than SimpleDateFormat? Parsing date with milliseconds

查看:591
本文介绍了DateTimeFormatter比SimpleDateFormat更严格吗?解析日期(以毫秒为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的测试用例:

I have simple test case:

public static void main(String[] args) {
  String pattern = "yyyy-MM-dd HH:mm:ss.SSS";
  String date = "2017-01-15 15:15:15.5";

  SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
  DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
  FastDateFormat fastDateFormat = FastDateFormat.getInstance(pattern);
  try {
    System.out.println("SFD: " + simpleDateFormat.parse(date));
  }catch (Exception e) {
    System.err.println("SDF failed");
  }
  try {
    System.out.println("DTF: " + dateTimeFormatter.parse(date));
  }catch (Exception e) {
    System.err.println("DTF failed");
  }
  try {
    System.out.println("FDF: " + fastDateFormat.parse(date));
  }catch (Exception e) {
    System.err.println("FDF failed");
  }
}

输出是这样的:

SFD: Thu Jan 15 15:15:15 CET 1970
DTF failed
FDF: Thu Jan 15 15:15:15 CET 1970

根据结果,Java的8 DateTimeFormatter比SimpleDateFormat更严格.我的问题是为什么,在那种情况下,什么是最好的方法来接受两个以.S作为毫秒或.SSS的日期,例如使用try/catch多次解析?

According to the results, Java's 8 DateTimeFormatter is more strict then SimpleDateFormat. My question is why and in that case, what would be best approach to accept both dates with .S as millis or .SSS, like parsing multiple times with try/catch ?

推荐答案

SimpleDateFormat的默认设置不是严格的,因为属性lenient的默认设置为true.但是您可以将属性lenient设置为false以使其严格.

SimpleDateFormat's is not strict per default, because the property lenient is true per default. But you can set the property lenient to false to make it strict.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
simpleDateFormat.setLenient(false);
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
try {
    System.out.println("SFD: " + simpleDateFormat.parse(date));
} catch (Exception e) {
    System.err.println("SDF failed");
}
try {
    System.out.println("DTF: " + dateTimeFormatter.parse(date));
} catch (Exception e) {
    System.err.println("DTF failed");
}

结果将是

SDF failed
DTF failed

请参见 DateFormat.parse(String,ParsePosition)

默认情况下,解析是宽松的:如果输入的格式不是此对象的format方法使用的格式,但仍可以将其解析为日期,则解析成功.客户可以通过调用setLenient(false)来坚持严格遵守该格式.

By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false).

这篇关于DateTimeFormatter比SimpleDateFormat更严格吗?解析日期(以毫秒为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆