Ganesh Satpute
Ganesh Satpute

Reputation: 3961

Java date string parse creates difference of timezone

I am bit frustrated by this.

I have a String "2015-02-18T23:44:59" which represents time in GMT format.

I want to parse this date into date object.

String dateStr = "2015-02-18T23:44:59";
Date date = DateUtils.parseDate(dateStr, new String[]{"yyyy-MM-dd'T'HH:mm:ss"});
System.out.println(dateStr + " \t" + date.toString());

This outputs :

2015-02-18T23:44:59     Thu Feb 19 05:14:59 IST 2015

As you can see latter time has time zone IST but my original time was GMT. I don't think there is any parse function which takes current date's time zone.

One way to answer is this question is that :

date.setTime(date.getTime() + ( date.getTimezoneOffset()  * 60 * 1000));
System.out.println("\t"  + date.toString());

This outputs:

Wed Feb 18 23:44:59 IST 2015

Which seems correct time (but incorrect time zone). Additionally, getTimezoneOffset() is deprecated.

Can anyone suggest me a better way to deal with String dates considering time zones.

Upvotes: 1

Views: 526

Answers (1)

ashosborne1
ashosborne1

Reputation: 2934

I'd use a date format:

SimpleDateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = utcFormat.parse("2015-02-18T23:44:59");

Upvotes: 3

Related Questions