Jer*_*gan 15 java timezone datetime timestamp
我有一个毫秒 - 自 - 本地 - 纪元时间戳,我想将其转换为自UTC时间戳的毫秒时间戳.从快速浏览文档看起来像这样的东西会起作用:
int offset = TimeZone.getDefault().getRawOffset();
long newTime = oldTime - offset;
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?
可悲的是,这似乎是最好的方法:
public static Date convertLocalTimestamp(long millis)
{
TimeZone tz = TimeZone.getDefault();
Calendar c = Calendar.getInstance(tz);
long localMillis = millis;
int offset, time;
c.set(1970, Calendar.JANUARY, 1, 0, 0, 0);
// Add milliseconds
while (localMillis > Integer.MAX_VALUE)
{
c.add(Calendar.MILLISECOND, Integer.MAX_VALUE);
localMillis -= Integer.MAX_VALUE;
}
c.add(Calendar.MILLISECOND, (int)localMillis);
// Stupidly, the Calendar will give us the wrong result if we use getTime() directly.
// Instead, we calculate the offset and do the math ourselves.
time = c.get(Calendar.MILLISECOND);
time += c.get(Calendar.SECOND) * 1000;
time += c.get(Calendar.MINUTE) * 60 * 1000;
time += c.get(Calendar.HOUR_OF_DAY) * 60 * 60 * 1000;
offset = tz.getOffset(c.get(Calendar.ERA), c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.DAY_OF_WEEK), time);
return new Date(millis - offset);
}
Run Code Online (Sandbox Code Playgroud)
(我知道这是发布日期后的几个月,但是在Android上使用短信时这是一个非常有用的问题.戴夫的回答是错误的.)
使用a Calendar来获取本地Epoch的偏移量,然后将其添加到local-epoch时间戳.
public static long getLocalToUtcDelta() {
Calendar local = Calendar.getInstance();
local.clear();
local.set(1970, Calendar.JANUARY, 1, 0, 0, 0);
return local.getTimeInMillis();
}
public static long converLocalTimeToUtcTime(long timeSinceLocalEpoch) {
return timeSinceLocalEpoch + getLocalToUtcDelta();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40383 次 |
| 最近记录: |