ITPub博客

首页 > 数据库 > 数据库开发技术 > 如何使用“dd MM”解析日期

如何使用“dd MM”解析日期

原创 数据库开发技术 作者:FunTester 时间:2020-02-27 08:46:02 0 删除 编辑

错误示范

本示例说明如何在不指定年份的情况下解析日期,如下:


package com.fun

import com.fun.frame.SourceCode

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

class TSSS extends SourceCode {

public static void main(String[] args) {
public static void main(String[] args) {

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM", Locale.CHINA);

String date = "02 12";

LocalDate localDate = LocalDate.parse(date, formatter);

System.out.println(localDate);

System.out.println(formatter.format(localDate));

}

}
}

输出

INFO-> 当前用户:fv,IP:192.168.0.100,工作目录:/Users/fv/Documents/workspace/fun/,系统编码格式:UTF-8,系统Mac OS X版本:10.15.3
Exception in thread "main" java.time.format.DateTimeParseException: Text '02 12' could not be parsed at index 3
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1947)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1849)
at java.time.LocalDate.parse(LocalDate.java:400)
at java_time_LocalDate$parse.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:115)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:135)
at com.fun.TSSS.main(TSSS.groovy:16)

Process finished with exit code 1

正解

模式dd MMM还不够;我们需要DateTimeFormatterBuilder为日期解析提供默认年份。


package com.fun

import com.fun.frame.SourceCode

import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatterBuilder
import java.time.temporal.ChronoField

class TSSS extends SourceCode {

public static void main(String[] args) {

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("dd MM")
.parseDefaulting(ChronoField.YEAR, 2020)
.toFormatter(Locale.CHINA);

String date = "02 11";

LocalDate localDate = LocalDate.parse(date, formatter);

System.out.println(localDate);

System.out.println(formatter.format(localDate));

}
}

输出

INFO-> 当前用户:fv,IP:192.168.0.100,工作目录:/Users/fv/Documents/workspace/fun/,系统编码格式:UTF-8,系统Mac OS X版本:10.15.3
2020-11-02
02 11

Process finished with exit code 0

  • 郑重声明:文章首发于公众号“FunTester”,禁止第三方(腾讯云除外)转载、发表。

技术类文章精选

非技术文章精选

原文作者:FunTester;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2019-07-07

  • 博文量
    1037
  • 访问量
    420847