如何使用DateTimeFormatter在java8中处理yyyy-mm和yyyy

Pra*_*ash 0 java date date-parsing java-8 java-time

我正在使用 SimpleDateFormat 来格式化或验证日期,但我想通过使用 java 8 DateTimeFormatter 使其成为线程安全的。我无法实现某些要求。

我的应用程序将只接受三种类型的格式。"yyyy-MM-dd", "yyyy-MM", "yyyy"

Existing Code gives me desired output:
/*simple date format to process yyyy-MM-dd format
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd")
/*simple date format to process yyyy-MM format
SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM")

/*simple date format to process yyyy format
SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy")

/* to parse input
simpleDateFormat.parse(input)
/* to format
simpleDateFormat.format(simpleDateFormat1)
Run Code Online (Sandbox Code Playgroud)

这是输入和预期输出:

  input             expected
'2018-03-19'       '2018-03-19'
'2018-03'          '2018-03'
'2018'             '2018'
'2017-02-54'       '2017-02'
'2016-13-19'       '2016'
Run Code Online (Sandbox Code Playgroud)
  1. 如何在 java 8 DateTimeFormat enter code hereter 中获得相同的结果?

    /* java 8 日期时间格式器 DateTimeFormatter dateTimeFormatter = new DateTimeFormatter("yyyy-MM-dd")

当所有年份、月份和日期值都正确时,上述代码段有效。任何帮助将不胜感激。

Bas*_*que 5

我正在使用 SimpleDateFormat 来格式化或验证日期

永远不要使用SimpleDateFormat.

与最早版本的 Java 捆绑在一起的糟糕的日期时间类在几年前就被JSR 310 中定义的现代java.time类所取代。

通过使用 java 8 DateTimeFormatter 实现线程安全

是的,与遗留的日期时间类不同,java.time类使用不可变对象并且在设计上是线程安全的。

这是输入和预期输出:

你的一些输入可以简单地通过它们的长度来检测。

// Ten-digits long, assume ISO 8601 date.
LocalDate ld = LocalDate.parse( "2018-03-19" ) ;

// Seven digits long, assume ISO 8601 year-month.
YearMonth ym = YearMonth.parse( "2018-03" ) ;

// Four digits, assume year.
Year y = Year.parse( "2018" ) ;
Run Code Online (Sandbox Code Playgroud)

请注意,上述输入均符合ISO 8601。该java.time类解析/生成字符串时,使用ISO 8601种格式默认。所以不需要指定格式模式。因此不需要明确的DateTimeFormatter对象。

'2017-02-54' '2017-02'

这个例子让我很困惑。如果您的意思是“当遇到日期无效的日期时,只需使用年份和月份而忽略日期”,我想您可以这样做。在DateTimeFormatter. 也许DateTimeFormatterBuilder用来构建一个灵活的DateTimeFormatter. 但坦率地说,我会拒绝将此类数据视为错误输入。生成可靠数据应该是数据发布者的工作,而不是消费者的工作来猜测错误数据背后的意图。

预期输入

'2016-13-19' '2016'

同样,在我不会玩的危险游戏中,试图猜测无效输入的有效部分。如果月份和日期无效,你怎么知道年份是有效的?更糟糕的是,如果这些数据的发布者可以发出如此错误的数据,你怎么知道一个表面上有效的2018-03-19输入实际上是正确的?如果月份13是错误的,怎么知道以月份的输入03也不是错误的?

将有关ISO 8601标准的问题数据传授给发布者,并要求他们修复错误。