Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unparseable date with extra number in Java

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.

like image 745
tok Avatar asked Sep 30 '16 10:09

tok


People also ask

How do you handle Unparseable date exception in Java?

Basically, this exception occurs due to the input string is not correspond with the pattern. You can try the below format: SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy", Locale.

How to get parse exception for date in java?

Date parsedDate = sdf. parse(date); SimpleDateFormat print = new SimpleDateFormat("MMM d, yyyy HH:mm:ss"); System. out. println(print.

What is SimpleDateFormat?

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.


2 Answers

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.

like image 165
Sergei Podlipaev Avatar answered Sep 23 '22 15:09

Sergei Podlipaev


Using a library where you can use fixed widths of four digits for the year would do the trick. Example for java.time-package in Java-8:

    String input = "201600101";

    DateTimeFormatter dtf =
        new DateTimeFormatterBuilder()
            .appendValue(ChronoField.YEAR, 4, 4, SignStyle.NEVER)
            .appendLiteral('0')
            .appendPattern("MMdd")
            .toFormatter();
    LocalDate date = LocalDate.parse(input, dtf);
    System.out.println(date); // 2016-01-01

This has the strong advantage not to be forced to change the input. It is always better to change the formatter. Admittingly, not possible with SimpleDateFormat.

like image 34
Meno Hochschild Avatar answered Sep 22 '22 15:09

Meno Hochschild