A subclass of the SimpleDateFormat class adds 1900 to the year

I created several subclasses of SimpleDateFormat to make it easier to work with the Azure feed I'm talking to on Android. One of them is as follows:

 public class ISO8601TLDateFormat extends SimpleDateFormat { private static String mISO8601T = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; public ISO8601TLDateFormat() { super(mISO8601T); } public ISO8601TLDateFormat(Locale inLocale) { super(mISO8601T, inLocale); } } 

As you can see, the intention is to produce or interpret dates similar to

2012-03-17T00: 00: 00,000 + 0100

what awaits waiting for Azure. However, when I load Date objects built from DatePicker like this:

 mDate = new Date(mDatePicker.getYear(), mDatePicker.getMonth(), mDatePicker.getDayOfMonth()); 

the output of ISO8601TLDateFormat is equal

3912-03-17T00: 00: 00,000 + 0100

As you can see, the year is 1900 more than me, or someone else not from the future . I carefully examined the Date object all the way to the Azure feed system, and it reports that its date is 2012, which I expected. Why is the gap SimpleDateFormat ?

+4
source share
1 answer

The problem is that Date constructors do not get what you expect. From java doc:

 public Date(int year, int month, int date) Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date). Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments. Parameters: year - the year minus 1900. month - the month between 0-11. date - the day of the month between 1-31. 

You need to keep in mind that you are building a date from 0, 0, 1 , starting January 1, 1900.

+4
source

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


All Articles