M_K
M_K

Reputation: 3455

Default Date year set at 1970

I need to parse a String that does not originally have the year set like "13 Aug 11:30"

but when I output the date it adds the year on, I tried set year but the year is totally wrong the output comes as "Thu Aug 13 11:30:00 GMT 3911"

Is there a way to set the year after the date is parsed?

SimpleDateFormat formatter = new SimpleDateFormat("dd MMM HH:mm");

String dateStr = "13 Aug 11:30";
Date fromDate = (Date)formatter.parse(dateStr);


fromDate.setYear(2011);

Upvotes: 6

Views: 15034

Answers (3)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

Use Calendar to set the year:

Calendar c = Calendar.getInstance();
c.setTime(fromDate);
c.set(Calendar.YEAR, 2011);
fromDate = c.getTime();

Upvotes: 11

user325117
user325117

Reputation:

The documentation for java.util.Date states quite clearly that setYear() adds 1900 to the year passed in. Just subtract 1900 from your argument.

Upvotes: 3

Jeffrey
Jeffrey

Reputation: 44808

Did you read the API for the setYear method?

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

2011 + 1900 = 3911

Upvotes: 3

Related Questions