2017-08-17 82 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()); 
相關問題