Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date TimeZone conversion in java?

I was looking for the simplest way to convert a date an time from GMT to my local time. Of course, having the proper DST dates considered and as standard as possible.

The most straight forward code I could come up with was:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String inpt = "2011-23-03 16:40:44";
Date inptdate = null;
try {
    inptdate = sdf.parse(inpt);
} catch (ParseException e) {e.printStackTrace();}   
Calendar tgmt = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
tgmt.setTime(inptdate);

Calendar tmad = new GregorianCalendar(TimeZone.getTimeZone("Europe/Madrid"));
tmad.setTime(inptdate);

System.out.println("GMT:\t\t" + sdf.format(tgmt.getTime()));
System.out.println("Europe/Madrid:\t" + sdf.format(tmad.getTime()));

But I think I didn't get the right concept for what getTime will return.

like image 377
filippo Avatar asked Mar 24 '11 16:03

filippo


People also ask

How do I convert between time zones in java?

To convert any time to the specific timezone (for example: UTC -> local timezone and vise versa) with any time pattern you can use java. time library. This method will take time patterns (original and required format) and timezone (original time zone and required timezone) will give String as output.

Does java date include timezone?

Using Java 7 The Date class (which represents a specific instant in time) doesn't contain any time zone information.

Which function changes date from one timezone to another?

setTimeZone() method to convert the date time to the given timezone.


1 Answers

The catch here is that the DateFormat class has a timezone. Try this example instead:

    SimpleDateFormat sdfgmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sdfgmt.setTimeZone(TimeZone.getTimeZone("GMT"));

    SimpleDateFormat sdfmad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sdfmad.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));

    String inpt = "2011-23-03 16:40:44";
    Date inptdate = null;
    try {
        inptdate = sdfgmt.parse(inpt);
    } catch (ParseException e) {e.printStackTrace();}

    System.out.println("GMT:\t\t" + sdfgmt.format(inptdate));
    System.out.println("Europe/Madrid:\t" + sdfmad.format(inptdate));
like image 129
Sebastiaan van den Broek Avatar answered Sep 20 '22 17:09

Sebastiaan van den Broek