简体   繁体   中英

Error converting date with two digits for the Year field

// 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'.

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.

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")) ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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