Hesam Hesam - 1 year ago 41
Java Question

Java, How to change GMT time to local time?

Server sends me time like this:

2012-06-08 17:00:00 +0100

I need to change it like
based on local time. For example this time is what time at Japan, India, US and etc.

How can I do this? Thanks

Answer Source

Option 1: using java.util.Date/Calendar:

First you need to parse the value to a Date, then reformat it in the format and time zone you're interested in:

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z",
Date date = inputFormat.parse(inputText);

// Potentially use the default locale. This will use the local time zone already.
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm", Locale.US);
String outputText = outputFormat.format(date);

Option 2: using Joda Time

Joda Time is a much better date/time library for Java.

DateTimeFormatter inputFormatter = DateTimeFormat
    .forPattern("yyyy-MM-dd HH:mm:ss Z")

DateTime parsed = inputFormatter.parseDateTime(inputText);

DateTimeFormatter outputFormatter = DateTimeFormat

String outputText = outputFormatter.print(parsed);

Note that you should only convert to/from string representations when you really need to. Otherwise, use the most appropriate type based on your usage - this is where Joda Time really shines.