我需要两件事:
将当前时间转换为UTC(因此我可以以UTC格式存储日期) - > result = java.util.Date。
将加载日期(UTC格式)转换为任何TimeZone - > 结果= java.util.Date或毫秒。
两点都要考虑到白昼。
1) 我在stackoverflow上找到了以下内容:
Calendar c = Calendar.getInstance();
System.out.println("current: "+c.getTime());
TimeZone z = c.getTimeZone();
int offset = z.getRawOffset();
if(z.inDaylightTime(new Date())){
offset = offset + z.getDSTSavings();
}
int offsetHrs = offset / 1000 / 60 / 60;
int offsetMins = offset / 1000 / 60 % 60;
System.out.println("offset: " + offsetHrs);
System.out.println("offset: " + offsetMins);
c.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
c.add(Calendar.MINUTE, (-offsetMins));
System.out.println("GMT Time: "+c.getTime());
- >结果等于UTC?
2)
public static long getTimeMillisFromTimeZone(long utcTimeMillis,
String timeZoneId) {
System.out.println("input millis: " + utcTimeMillis);
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.setTimeInMillis(utcTimeMillis);
TimeZone fromTimeZone = calendar.getTimeZone();
TimeZone toTimeZone = TimeZone.getTimeZone(timeZoneId);
calendar.setTimeZone(fromTimeZone);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone()
.getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}
System.out.println(calendar.getTime());
System.out.println("output millis: " + calendar.getTime().getTime());
return calendar.getTime().getTime();
}
- >我在那里遇到了问题 - >输了1h!
在我的例子中,我将来自TimeZone“Europe / Vienna”的日期(使用日光)存储到数据库中作为utc。 欧洲/维也纳 - > 10:00 UTC - > 09:00
现在我想将此UTC(09:00)转换为“欧洲/维也纳”,我得到:09:00 =我失去了一个小时..
答案 0 :(得分:2)
答案 1 :(得分:0)
请尝试使用以下代码(我使用 Joda时间)来转换时区之间的日期:
public static Date convertDate(Date sourceDate, DateTimeZone sourceTimeZone, DateTimeZone resultTimeZone) {
LocalDateTime localDateTime = new LocalDateTime(date.getTime());
DateTime sourceDateTime = localDateTime.toDateTime(sourceTimeZone);
DateTime resultDateTime = sourceDateTime.withZone(resultTimeZone);
return resultDateTime.toLocalDateTime().toDateTime().toDate();
}
转换为 UTC 可以简化为:
public static Date toUtcDate(Date sourceDate, DateTimeZone sourceTimeZone) {
return convertDate(sourceDate, sourceTimeZone, DateTimeZone.UTC);
}
此调用成功为我增加了1小时:
convertDate(new Date(), DateTimeZone.UTC, DateTimeZone.forID("Europe/Vienna"));