2015-10-25 126 views
0

我收到一個時間字符串,例如14:26:16,它指的是今天。 我的要求是找出當前時間和給定時間之間的差異。SimpleDateFormat分析當前日期的時間字符串

SimpleDateFormat解析字符串沒有異常,但不是得到25/10/2015 14:26:16我得到01/01/1970 14:26:16。聽起來很簡單,我還沒有想出一個簡單的方法來解析正確的日期。

我當前的代碼:

SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); 
Date currentTime = new Date(); //25/10/2015 
Date arrivalTime = formatter.parse(eta); //01/01/1970 
final long difference = arrivalTime.getTime() - currentTime.getTime(); 
+0

您使用的是哪個Java版本?舊的'Date'和相關的類現在已經過時了,如果你正在編寫新的代碼,你應該使用Java 8 java.time,或者使用舊的Java JodaTime。 – RealSkeptic

+0

我沒有提到我正在開發Android。它仍然適用?我正在使用JRE 1.8.0_45,但未能導入包的類。 –

+0

您不能在Android上使用Java 8,它只支持Java 7 – Shmuel

回答

1

這是Java 7中,將與Android合作。

/** 
* Android utility to get the elapsed milliseconds between a String timestamp (in the future) and the current time 
* @param timeStamp Accepts a String in the form of HH:mm:ss 
* @return Elapsed time in milliseconds 
* @throws ParseException 
*/ 
public static long timeDiff(String timeStamp) throws ParseException { 
    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); 
    Date arrivalTime = formatter.parse(timeStamp); 

    Calendar arrivalCal= Calendar.getInstance(); 
    arrivalCal.set(Calendar.HOUR_OF_DAY, arrivalTime.getHours()); 
    arrivalCal.set(Calendar.MINUTE, arrivalTime.getMinutes()); 
    arrivalCal.set(Calendar.SECOND, arrivalTime.getSeconds()); 
    arrivalCal.set(Calendar.MILLISECOND, 0); 

    return arrivalCal.getTimeInMillis() - System.currentTimeMillis(); 
} 

爲了解決上述評論有關喬達時間,喬達是一個偉大的時刻實用程序庫,但它會大量的開銷添加到您的項目。如果您反覆需要編寫時間轉換方法,那麼您可能應該轉向Joda,但只有一種方法不能保證項目的額外成本。

+0

我對使用這些棄用的方法有點擔心,但是由於此處的討論,我發現它可能是我的項目的正確解決方案(日期操縱部分確實很小)。謝謝! –

2

我建議使用LocalTime 像這樣的事情

LocalTime arrivalTime = LocalTime.parse(eta, DateTimeFormatter.ISO_LOCAL_TIME); 
LocalTime currentTime = LocalTime.now(); 
final long difference = arrivalTime.getLong(ChronoField.MILLI_OF_DAY) - currentTime.getLong(ChronoField.MILLI_OF_DAY); 
+0

https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html#minus-long-java .time.temporal.TemporalUnit-可以讓事情變得更好恕我直言 –

+0

@RC。是的,這看起來更好,但我只是改編現有的代碼到新的日期API :) –

+0

我認爲使用'Duration.between(currentTime,arrivalTime).toMillis()'會更好。 – RealSkeptic

相關問題