问题描述
我一直在寻找将时间从 GMT 转换为本地时间的最简单方法.当然,要考虑正确的 DST 日期并尽可能标准.
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: " + sdf.format(tgmt.getTime())); System.out.println("Europe/Madrid: " + sdf.format(tmad.getTime()));
但我认为我没有正确理解 getTime 将返回的内容.
But I think I didn't get the right concept for what getTime will return.
推荐答案
这里的问题是 DateFormat 类有一个时区.试试这个例子:
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: " + sdfgmt.format(inptdate)); System.out.println("Europe/Madrid: " + sdfmad.format(inptdate));