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.
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.
Using Java 7 The Date class (which represents a specific instant in time) doesn't contain any time zone information.
setTimeZone() method to convert the date time to the given timezone.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With