Arya Arya - 1 month ago 5
Java Question

Adding year to parsed date

I am parsing the following string as a date


Oct., 19 at 22:41


SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("MMM., d 'at' H:mm");
dateAndTimeOfMessageRecivedDate = simpleDateFormat1.parse(date);
dateAndTimeOfMessageRecivedDate.setYear(2016);


But when I print the
dateAndTimeOfMessageRecivedDate
it looks like this


Thu Oct 19 22:41:00 EDT 3916


Shouldn't the year be 2016? why is it 3916?

Answer

As per javadocs

Sets the year of this Date object to be the specified value plus 1900

Also note

Deprecated. As of JDK version 1.1, replaced by Calendar.set(Calendar.YEAR, year + 1900).

So you should use

Calendar cal = Calendar.getInstance();
cal.setTime (dateAndTimeOfMessageRecivedDate);
cal.set(Calendar.YEAR, 2016);
Comments