Nested exception is java.time.format.DateTimeParseException: Text ‘3030821’

huangapple go评论77阅读模式
英文:

Nested exception is java.time.format.DateTimeParseException: Text '3030821'

问题

如何将这个字符串解析为日期:

3030821

格式为:

303-08-21

我指的是公元年份(Anno Domini)。

我希望这个解决方案也能适用于类似 20200820 的字符串。

英文:

How can I parse this String

3030821  

to date like

303-08-21 

I mean AD year (Anno Domini),

I would also like this solution to be resistant to String like 20200820

答案1

得分: 2

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

public class Main {
    public static void main(String[] args) {
        LocalDate date = LocalDate.parse("3030821", DateTimeFormatter.ofPattern("uuuMMdd"));
        System.out.println(date.format(DateTimeFormatter.ofPattern("u-MM-dd")));

        date = LocalDate.parse("20200820", DateTimeFormatter.ofPattern("uuuMMdd"));
        System.out.println(date.format(DateTimeFormatter.ofPattern("u-MM-dd")));
    }
}

Output:

303-08-21
2020-08-20

Learn more about the modern date-time API at Trail: Date Time.

英文:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
	public static void main(String[] args) {
		LocalDate date = LocalDate.parse("3030821", DateTimeFormatter.ofPattern("uuuMMdd"));
		System.out.println(date.format(DateTimeFormatter.ofPattern("u-MM-dd")));

		date = LocalDate.parse("20200820", DateTimeFormatter.ofPattern("uuuMMdd"));
		System.out.println(date.format(DateTimeFormatter.ofPattern("u-MM-dd")));
	}
}

Output:

303-08-21
2020-08-20

Learn more about the modern date-time API at Trail: Date Time.

huangapple
  • 本文由 发表于 2020年10月17日 04:56:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64396290.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定