2017-08-17 68 views
-1

我试图做一个发布UTC时间戳的差别:检查分钟,直到事件。 (我在中央时间,UTC -5小时)。 我得到的对象是一个JSON元素,看起来像这样,当我把字符串:查找分钟从当前时间

/日期(1502964420000-0500)/

我应该能够:

//take the departure time and subtract it from the current time. Divide by 60 
    timeStamp = timeStamp.substring(6,16); 

这使我1502964420,我可以用时间转换器来获得:周四,2017年8月17日上午5时07分00秒

问题是..我如何获得当前时间以相同的格式减去了吗? (或者,如果有更好的方式来做到这一点,我会很乐意采取的建议为好)。

+0

1502964420在我看来,这是从时代开始秒。你如何以相同的格式获得当前时间?我推荐[这个答案](https://stackoverflow.com/a/43687687/5772882)。 –

+0

的可能的复制[如何找到秒钟,因为在1970年的Java(https://stackoverflow.com/questions/8263148/how-to-find-seconds-since-1970-in-java) –

回答

0

您可以使用Date currentDate = new Date()然后currentDate.getTime()来得到当前Unix时间以毫秒为单位或使用Calendar -class:Calendar currentDate = Calendar.getInstance()currentDate.getTime().getTime()来得到当前Unix时间以毫秒为单位。

你可以做同样的从JSON解析的日期,然后计算出两个值之间的差异。要获得分钟的差别,只是把它再由(60 * 1000)

+0

想法是正确的,请不要教导年轻人使用长期过时的课程“日期”和“日历”。今天我们好多了。我推荐'Instant'类。 –

1

我会建议看数据类型ZonedDateTime

有了这个,你可以很容易地进行calculasions和转换这样的:

ZonedDateTime startTime = ZonedDateTime.now(); 
Instant timestamp = startTime.toInstant(); // You can also convert to timestamp 
ZonedDateTime endTime = startTime.plusSeconds(30); 

Duration duration = Duration.between(startTime, endTime); 

if(duration.isNegative()){ 
    // The end is before the start 
} 

long secondsBetween = duration.toMillis(); // duration between to seconds 

既然你不知道ZonedDateTime这里是一个快速概述如何字符串转换为ZonedDateTime:

注意:该字符串是在ISO8601格式!

String example = "2017-08-17T09:14+02:00"; 
OffsetDateTime offset = OffsetDateTime.parse(example); 
ZonedDateTime result = offset.atZoneSameInstant(ZoneId.systemDefault()); 
相关问题