Java getDate 0000/00/00 returns a strange value

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

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

Output:

 Sun Nov 30 00:00:00 GMT 2 
+6
source share
3 answers

There is no year in the Gregorian calendar.

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

Since you supply 0 per month and 0 per day, it returns to the previous month and previous year.

those. 30-Nov-0002 BCE.

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

If you intend to work with dates that are far back, you need to consult a historian.

+14
source

The starting point for the date will be 00010101 ei Year - 1, Month - Jan and Date - 1

What you entered is 00000000

Starting from the month - 00 means Jan - 1 i.e. Dec

Day 00 means 1 Dec - 1 i.e. 30th Nov

This explains the first part of the conclusion. Sun Nov 30 00:00:00 GMT

The year is 00 , which means year 1 minus 1. i.e. 1 BC And as the year rolls off again during the month and its date 2 BC

Therefore, the year is shown as 2.

+4
source

By default, SimpleDateFormat tries to parse even incorrect input. You can disable this with the setLenient method:

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

So 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) 
+4
source

Source: https://habr.com/ru/post/987735/


All Articles