简体   繁体   English

在java.time中格式化日期

[英]Formatting date in java.time

I am trying to format date were is given in following format 05051988 . 我正在尝试格式化日期,格式为05051988 I want to use LocalDate to format in next 05 may 1988 . 我想在05 may 1988使用LocalDate进行格式化。

I have create private method that i will use later in same class to input formatted date in text. 我创建了私有方法,稍后我将在同一类中使用该方法在文本中输入格式化的日期。 I have already made some code but i at the moment I'm getting 1988-05-05 if I use MM , if I replace it with MMM then it is giving me error message that can not be parsed. 我已经编写了一些代码,但是如果使用MM ,则此刻我会得到1988-05-05 ,如果我将其替换为MMM ,则会出现无法解析的错误消息。

private LocalDate parseDate(){
    LocalDate dateOfBirth = LocalDate.parse(date, DateTimeFormatter.ofPattern("ddMMyyyy"));
    return dateOfBirth;
}

Error: 错误:

Exception in thread "main" java.time.format.DateTimeParseException: Text '05051988' could not be parsed at index 2

You still need to use "ddMMyyyy" to parse the date. 您仍然需要使用“ ddMMyyyy”来解析日期。 Then use "dd MMM yyyy" to format it when you print it. 然后在打印时使用“ dd MMM yyyy”对其进行格式化。

Something like this: 像这样:

String reformat(String dateOfBirth) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyy");
    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd MMM yyyy");
    LocalDate date = LocalDate.parse(dateOfBirth, fomatter);
    return formatter2.print(date);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM