Date TimeZone conversion in java?(java中的日期时区转换?)
问题描述
我一直在寻找将时间从 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));
这篇关于java中的日期时区转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:java中的日期时区转换?
基础教程推荐
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 从 python 访问 JVM 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
