[英]How to compare if current Time is greater than other Time in Java?
我有一個后端作業,它在一天內運行一次,並根據實體/用戶等安排在特定時間。
現在,我想驗證當前時間是否早於工作,如果是,那么可以重新安排工作,否則如果工作已經過去,那么當然不能重新安排當天的工作。
public static String getCurrentTime(String format) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(cal.getTime());
}
String time = getCurrentTime("yyyy-MM-dd HH:mm:ss");
String backendJobTime = getBackendJobSchedule();
String[] onlyTime = time.split("\\s+");
String time = onlyTime[1];
Integer.parseInt(time);
后端工作也一樣
if(time < backendJob){
system.out.println("Job is yet to be exectued...):
}
現在,我想獲得 substring 的時間,然后與后端作業的其他時間進行比較,看看它是否更早。 我寫不出完整的邏輯。
謝謝。
if(
Instant
.parse( "2022-07-14T22:15:00Z" )
.isBefore(
Instant.now()
)
) { … }
永遠不要使用糟糕的遺留日期時間類Date
、 Calendar
、 SimpleDateFormat
。 這些在幾年前被 JSR 310 中定義的現代java.time類所取代。
你說:
getCurrentTime("yyyy-MM-dd HH:mm:ss")
您需要的不僅僅是日期和時間來跟蹤某個時刻。 對於時間線上的特定點,您需要時區的上下文或與 UTC 的偏移量。
在 Java 中,以Instant
object 的形式跟蹤時刻。 這個 class 代表一個時刻,從 UTC 偏移零時分秒。
Instant instant = Instant.now() ;
要序列化為文本,請使用標准 ISO 8601 格式。
String output = instant.toString() ;
2022-01-23T15:30:57.123456Z
Z
表示零偏移。 發音為“祖魯語”。
並解析:
Instant instant = Instant.parse( "2022-01-23T15:30:57.123456Z" ) ;
通過調用isBefore
、 isAfter
和equals
進行比較。
if( instant.isBefore( Instant.now() ) ) { … }
請注意,上面的代碼中沒有涉及時區。 也許您想根據自己的時區設置目標時間。
實例化ZonedDateTime
object。 提取Instant
以適應 UTC(零偏移)。
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalDate ld = LocalDate.of( 2022 , Month.MARCH , 23 ) ;
LocalTime lt = LocalTime.of( 15 , 30 ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Instant instant = zdt.toInstant() ;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.