Gonçalo Cardoso
Gonçalo Cardoso

Reputation: 2262

Java getDate 0000/00/00 return strange value

Why does this happens? For the month and day, I think Java is assuming the previous valid month and day, but I don't understand why year is 2.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date result = sdf.parse("0000/00/00");

System.out.println(result.toString());

Output is:

Sun Nov 30 00:00:00 GMT 2

Upvotes: 9

Views: 3467

Answers (3)

Bathsheba
Bathsheba

Reputation: 234795

The Gregorian calendar does not have year 0.

Year 0 corresponds to 1BCE (Before Common Era, also known as BC).

Because you supply 0 for the month and 0 for the day, it rolls back to the previous month and previous year.

I.e. 30-Nov-0002 BCE.

Date#toString does not include BCE / CE suffix. It would be superfluous in the vast majority of cases.

If you are going to work with dates that far back then you need to consult with an historian.

Upvotes: 18

Tagir Valeev
Tagir Valeev

Reputation: 100279

By default SimpleDateFormat tries to parse even incorrect input. You can switch this off using setLenient method:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
sdf.setLenient(false);
Date result = sdf.parse("0000/00/00");

This way you will have an exception which is probably more appropriate in your case:

Exception in thread "main" java.text.ParseException: Unparseable date: "0000/00/00"
    at java.text.DateFormat.parse(DateFormat.java:366)
    at Snippet.main(Snippet.java:11)

Upvotes: 6

Subir Kumar Sao
Subir Kumar Sao

Reputation: 8411

The starting point for Date would be 00010101 ei Year - 1 , Month - Jan and Date - 1

What you have given input is 00000000

Will start with month - 00 means Jan - 1 ie Dec

Day 00 mean 1 Dec - 1 ie 30th Nov

This explains the 1st part of the output. Sun Nov 30 00:00:00 GMT

The year is given 00 that mean year 1 minus 1 . ie 1 BC And as year rolls back another time for month and date its 2 BC.

Hence the year is shown as 2.

Upvotes: 4

Related Questions