Date timezone conversion in Java?
•
Java
The most direct code I can think of is:
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 don't think I got the correct concept that gettime will return
Solution
The problem here is that the dateformat class has a time zone Try this example:
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));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码