0

I am getting a date/time string from web in the format of yyyy-mm-dd HH:MM:SS and it is in UTC.

I have to create a Date object and print the date object in GMT format, but I don't want the to change, for example if I read the date as 2014-10-22 09:00:00, then it should be displayed as 2014-10-22 09:00:00 GMT instead of 2014-10-22 13:30:00

How do I do this? Please suggest me.

(FYI, Currently, UTC time is 10:25 AM, in india current time is 3:55 PM).

I am using Jaxb parser to parse the XML. Any suggestions are invited

msrd0
  • 7,816
  • 9
  • 47
  • 82
Ambuj Jauhari
  • 1,187
  • 4
  • 26
  • 46
  • GMT isn't a format - it's effectively a time zone. What you've described so far is almost an identity conversion: `public static String convert(String text) { return text + " GMT"; }`... And at the time of posting, the UTC time was roughly 16:34, *not* 10:25... – Jon Skeet Oct 16 '14 at 16:36
  • possible duplicate of [Format date in java](http://stackoverflow.com/questions/4772425/format-date-in-java) – msrd0 Oct 16 '14 at 16:36

1 Answers1

0

You could use a SimpleDateFormat to parse the date, and then reformat it to a different timezone.

String toTimeZone = "GMT";
String fromTimeZone = "UTC";
String stingvalue = "2014-10-14 03:05:39";

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone(fromTimeZone));
Date parsedDate = dateFormat.parse(stingvalue);

dateFormat.setTimeZone(TimeZone.getTimeZone(toTimeZone));

String newDate = dateFormat.format(parsedDate);

Explanation

The Java Date class counts time in milliseconds from January 1, 1970 00:00:00.000 GMT. As such, your Dates are time zone neutral. To get date in a different time zone, simply format it differently

PeterK
  • 1,697
  • 10
  • 20
  • The thing is we have a UI to which we pass the java.util.date variable. Hence i need to pass the Date variable created in GMT timeZone. I cannot pass string to the UI – Ambuj Jauhari Oct 16 '14 at 16:53
  • In that case, you'll just need to create a `SimpleDateFormat` as per your required format, set the time zone and format the date. That should do the trick. – PeterK Oct 16 '14 at 17:22