在我的应用程序中,第三方API之一在纪元中返回时间戳。
有时它以秒为单位返回划时代的时间,有时以毫秒为单位返回未确认的时间。我的应用程序使用下面的代码将其转换为java日期并将其显示给用户,但是当我收到以毫秒为单位的时间时,它在一年内就失败了。
String time = "1519377196185"; //Time in miliseconds
//String time = "1521575819"; //Time in seconds.
String timeZone = "US/Pacific";
long epochdate = Long.parseLong(time);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy hh:mm a");
LocalDateTime date34 =
Instant.ofEpochSecond(epochdate)
.atZone(ZoneId.of(timeZone))
.toLocalDateTime();
String date = date34.format(formatter).toString();
System.out.println("date : " + date);如果我使用Instant.ofEpochMilli(epochdate)几毫秒,那么它就能正常工作。因此,我的问题是如何知道即将到来的时间戳以毫秒或秒为单位,因此在此基础上,我将在ofEpochMilli和ofEpochSecond之间切换
发布于 2018-03-21 02:29:42
年偏移量
我将尝试首先将日期解析为秒,如果日期以millis为单位,则年份将非常大(在本例中为50000),如果该年份不大于定义偏移量的年份(例如,3000),则返回该日期,否则该日期将作为millis返回。
public ZonedDateTime getZonedDateTime(String time) {
long longTime = Long.parseLong(time), yearOffset = 3000L;
String timeZone = "US/Pacific";
ZoneId zoneId = ZoneId.of(timeZone);
ZonedDateTime zdt = Instant.ofEpochSecond(longTime).atZone(zoneId);
if (zdt.getLong(ChronoField.YEAR_OF_ERA) >= yearOffset) {
return Instant.ofEpochMilli(longTime).atZone(zoneId);
} else {
return zdt;
}
}使用函数打印:
getZonedDateTime("1519377196185"); // 2018-02-23T01:13:16.185-08:00[US/Pacific]
getZonedDateTime("1521575819"); // 2018-03-20T12:56:59-07:00[US/Pacific]误差裕度
您决定使用的任何方法都有出错的可能,并且日期转换不正确,特别是当日期以毫秒为单位,且与时代1970-01-01T00:00:00Z太近时。
使用3000的年份偏移量的保证金错误如下:
计算误差范围,以毫秒为单位,日期为
您可以使用以下方法计算日期的错误范围(最初以毫秒为单位):
Instant.ofEpochMilli(LocalDateTime.of(3000, 1, 1, 0, 0) // year = 3000
.toEpochSecond(ZoneOffset.UTC)); // 1971-01-12T04:48:00Z发布于 2018-03-20 22:01:07
一个简单的(临时的,某种程度的)解决方案是检查time String的长度。如果长度等于13,则表示毫秒。这将是正确的,直到1 ms之后的2286-11-20T17:46:39.999Z,这是一个很长的时间后,现在。以秒为单位的时间将需要更多的时间到达一个长度的13。
发布于 2018-03-20 22:05:06
您可以用另一种方法解决这一问题,方法是以秒为单位将历法转换为以毫秒为单位的历次,并且只对这两种方法应用Instant.ofEpochMilli():
String time = "1519377196185"; //Time in miliseconds or seconds
if(time.length() == 10) { // length of epoch in seconds is 10
time = time + "000";
}
String timeZone = "US/Pacific";
long epochdate = Long.parseLong(time);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy hh:mm a");
LocalDateTime date34 = Instant.ofEpochMilli(time)
.atZone(ZoneId.of(timeZone))
.toLocalDateTime();
String date = date34.format(formatter).toString();
System.out.println("date: " + date);https://stackoverflow.com/questions/49394698
复制相似问题