问题
// input format: dd/MM/yy
SimpleDateFormat parser = new SimpleDateFormat("dd/MM/yy");
// output format: yyyy-MM-dd
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(formatter.format(parser.parse("12/1/20"))); // 0020-11-01
I am using the above code but it is giving me year as '0020' instead of '2020'.
回答1:
Use java.time
for this:
public static void main(String[] args) {
String dateString = "12/1/20";
LocalDate localDate = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("dd/M/yy"));
System.out.println(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
The output is
2020-01-12
Pay attention to the amount of M
in the patterns, you cannot parse a String
that contains a single digit for a month using a double M
here.
回答2:
Most Java devs would be tempted to answer SimpleDateFormat but it's not thread safe.
So I recommend you use Java 8 DateFormat.
Assuming your current Date is a String:
DateFormat dateFormat = new DateFormat("yyyy-MM-dd") ;
String dateString ="20/4/20";
LocalDate date = LocalDate.parse(dateString, dateFormat);
If you are using less than Java 8 use joda time for the same classes. Once you have converted it as a date object use required format and use LocalDate.
format(date, new DateFormat("yyyy-MM-dd")) ;
来源:https://stackoverflow.com/questions/60393945/error-converting-date-with-two-digits-for-the-year-field