【发布时间】:2018-10-01 22:05:47
【问题描述】:
将服务器日期转换为设备本地时间的功能:
public static String convertIntoLocalTime(String strTime, String whichTimeZone, String dateFormat) {
String strLocalTime = null;
try {
SimpleDateFormat sdf = getSimpleDateFormat(dateFormat, whichTimeZone);
Date date = sdf.parse(strTime);
AppLog.e(TAG,"Timezone = " + whichTimeZone);
AppLog.e(TAG,"Date = " + strTime);
AppLog.e(TAG,"Date in CET = " + date.toString());
AppLog.e(TAG,"inDaylightTime = " + sdf.getTimeZone().inDaylightTime(date));
AppLog.e(TAG,"DST savings = " + sdf.getTimeZone().getDSTSavings());
if (sdf.getTimeZone().getDSTSavings() == 3600000) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, 1);
Date oneHourBack = cal.getTime();
SimpleDateFormat local = getLocalSimpleDateFormat(dateFormat);
strLocalTime = local.format(oneHourBack);
} else {
SimpleDateFormat local = getLocalSimpleDateFormat(dateFormat);
strLocalTime = local.format(date);
}
} catch (ParseException e) {
AppLog.e(TAG, e.getMessage(), e);
}
AppLog.e(TAG,"Local Time = " + strLocalTime);
return strLocalTime;
}
获取简单日期格式的函数:
private static SimpleDateFormat getSimpleDateFormat(String format, String tz) {
TimeZone timeZone = TimeZone.getTimeZone(tz);
timeZone.useDaylightTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, Locale.getDefault());
simpleDateFormat.setTimeZone(timeZone);
return simpleDateFormat;
}
获取本地设备转换的简单日期格式的功能:
/**
* @param format
* @return
*/
private static SimpleDateFormat getLocalSimpleDateFormat(String format) {
TimeZone timeZone = TimeZone.getDefault();
timeZone.useDaylightTime();
SimpleDateFormat localSdf = new SimpleDateFormat(format, Locale.getDefault());
localSdf.setTimeZone(timeZone);
return localSdf;
}
输出:
日期 = 2018-04-22 14:30
CET 日期 = 2018 年 4 月 22 日星期日 13:30:00 GMT+01:00 2018
inDaylightTime = true
DST 节省 = 3600000
当地时间 = 2018-04-22 14:30
上面的代码之前运行得非常好,例如,我们在 4 月 1 日有 1 个事件正确显示时间,但从 4 月 21 日开始,它显示了额外的 1 小时时间。
我尝试使用 UTC 和 CET 转换来自服务器的日期,但在这两种情况下,当将其转换为设备本地时间时,它都会显示额外的一小时。
以上示例基于伦敦时区,而当我们在 IST 时区尝试时,它返回了正确的时间。
我们通过检查时区的inDaylightTime 函数处理了不同的 DST 时间,但它不起作用。
我确信有些东西与 DST 相关,但我无法弄清楚。感谢您的帮助?
【问题讨论】:
-
欢迎来到 SO。请查看此处了解如何改进您的问题(格式化、校对、提供代码等):stackoverflow.com/help/how-to-ask
-
好的。谢谢会检查。
-
@JahanviKariya 我认为你需要使用github.com/dlew/joda-time-android 因为android Calendar 有一些错误
-
@VishalThakkar 这很奇怪,您对这些错误有任何了解吗?我的意思是任何参考链接来验证这一点,因为我在 iOS Swift 3 上也遇到了同样的问题。
-
@JahanviKariya stackoverflow.com/questions/44346152/…
标签: java android datetime dst timezone-offset