英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论