如果当前时间大于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...):
}

现在,我想得到时间的子字符串,然后与后端作业的其他时间进行比较,看看它是否更早。我写不出完整的逻辑。

tl;dr

if(
Instant
.parse( "2022-07-14T22:15:00Z" )
.isBefore( 
Instant.now() 
)
) { … }

详细信息

永远不要使用糟糕的遗留日期时间类DateCalendarSimpleDateFormat。这些在几年前被JSR310中定义的现代java.time类所取代。

你说:

getCurrentTime("yyyy-MM-dd HH:MM:ss"(

您需要的不仅仅是一天中的日期和时间来跟踪一个时刻。对于时间线上的特定点,您需要时区或UTC偏移量的上下文。

在Java中,将时刻作为Instant对象进行跟踪。此类表示从UTC偏移0小时-分-秒的时刻。

Instant instant = Instant.now() ;

要序列化为文本,请使用标准ISO 8601格式。

String output = instant.toString() ;

2022-01-23T15:30:57.12346Z

Z表示偏移量为零。发音为"祖鲁"。

并解析:

Instant instant = Instant.parse( "2022-01-23T15:30:57.123456Z" ) ;

通过调用isBeforeisAfterequals进行比较。

if( instant.isBefore( Instant.now() ) ) { … }

请注意,上面的代码中没有涉及时区。也许你想按照自己的时区设置目标时间。

实例化一个ZonedDateTime对象。提取一个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() ;

相关内容

最新更新