Unparseable date with extra number in Java

tok :

What's wrong in this code? I'm trying to parse a date format that has 0 between years and months.

import java.text.SimpleDateFormat;

class Main {
    public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy'0'MMdd");
        try {
            Date date = format.parse("201600101");
            System.out.println(date);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

This outputs Unparseable date: "201600101". If I change '0' to anything but number [e.g. 'X' and format.parse("2016X0101")] this will work.

Sergei Podlipaev :

As Peter Lawrey said Java sees '20160' as a year. You can solve your problem by modifying "201600101" to, for example, 2016-00101 and refactor your format patter as

SimpleDateFormat format = new SimpleDateFormat("yyyy-'0'MMdd");

That will parse your date.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=457478&siteId=1