Java UTC Time
程序开发
2023-09-03 12:57:24
2019独角兽企业重金招聘Python工程师标准>>>
项目需要把 long 转换成 Timestamp,而且需要是 UTC 时间。
网上 google了好久,总结了这个写法
Calendar cal = Calendar.getInstance();
long value = cal.getTimeInMillis(); //your long value.
int zoneOffset = cal.get(Calendar.ZONE_OFFSET);
int dstOffset = cal.get(Calendar.DST_OFFSET);
cal.setTimeInMillis(value);
cal.add(Calendar.MILLISECOND, -(zoneOffset+dstOffset)); //it only takes int int
System.out.println(new Timestamp(cal.getTimeInMillis()));
update
public static Timestamp getUTCTimestamp(final long value){ long v2 = value;Calendar cal = Calendar.getInstance();TimeZone tz = cal.getTimeZone();long offset = tz.getOffset(value);v2 = value - offset; //v2 is local time return new Timestamp(v2); }
Another Update: from TimeZone to TimeZone
public void getTime(long time, TimeZone toTimeZone) {Calendar cal = Calendar.getInstance();cal.setTimeInMillis(time);int zoneOffset = cal.get(Calendar.ZONE_OFFSET); // Get TimeZone differenceint dstOffset = cal.get(Calendar.DST_OFFSET); // Get summer time difference// logger.debug("To UTC: {} ,{} ",zoneOffset,dstOffset);cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset)); // now update the timeint zoneOffset2 = toTimeZone.getRawOffset();int dstOffset2 = 0;cal.add(Calendar.MILLISECOND, (zoneOffset2));if (toTimeZone.inDaylightTime(cal.getTime())) {dstOffset2 = toTimeZone.getDSTSavings();cal.add(Calendar.MILLISECOND, (dstOffset2));}//logger.debug("To UTC: {} ,{} ", zoneOffset2, dstOffset2);Timestamp ts = new Timestamp(cal.getTimeInMillis());logger.debug("{} := {} ", toTimeZone.getDisplayName(), ts);}
update
public static Timestamp getTimStampInTimeZone(final long value, TimeZone toTimeZone){long v2 = value;Calendar cal = Calendar.getInstance();TimeZone tz = cal.getTimeZone();long offset = tz.getOffset(value);v2 = value - offset; //v2 is local timelong offset2 = toTimeZone.getOffset(v2);v2 += offset2; return new Timestamp(v2);}
转载于:https://my.oschina.net/u/1767744/blog/294709
标签:
上一篇:
【前端项目问题】如何运行angular项目使局域网内的电脑都可以访问到本地项目
下一篇:
前端项目F5刷新,报错:‘crbug1173575, non-JS module files deprecated’ 的问题根源和解决方法
相关文章
-
无相关信息