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.
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.
Date parsedDate = sdf. parse(date); SimpleDateFormat print = new SimpleDateFormat("MMM d, yyyy HH:mm:ss"); System. out. println(print.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With