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.
You need to set the
TimeZone
on theSimpleDateFormat
, usingDateFormat.setTimeZone()
.The catch here is that the DateFormat class has a timezone. Try this example instead:
The simplest way is to use a decent date-time library rather than the notoriously troublesome java.util.Date and .Calendar classes. Instead use either Joda-Time or the java.time package found in Java 8.
Joda-Time
For the input, you can simply add the Timezone to the String (note the 'z' in the format):
Here is the 2017 answer.
Please enjoy how much more naturally this code expresses the intent.
The code prints
(with tab size of 8 it aligns nicely, but StackOverflow seems to apply a tab size of 4).
I swapped
23
and03
in your input string, I believe you intended this. BTW, it wasn’t me catching your mistake, it wasLocalDateTime.parse()
throwing an exception because there is no 23rd month. Also in this respect the modern classes are more helpful than the outdated ones.Joda-Time? Basil Bourque’s answer mentions and recommends both
java.time
, which I am using, and Joda-Time. While Joda-Time is already a sizeable improvement over the outdated classes used in the question (SimpleDateFormat
,Calendar
,GregorianCalendar
), it is by now in maintenance mode; no greater further development is expected.java.time
is hugely inspired by Joda-Time. For new code, I see no reason why you shouldn’t preferjava.time
.