我对Java很陌生。我有一个要求计算的天数,小时,时间,秒从一个给定的日期到今天,当前时间。
例如,我从数据库中获得两个字段:Date和Time。
Date字段为格式Wednesday 02-October-2022,Time字段为格式11:51:1 PM。
在我的Java类中,我能够以字符串格式传递这两个字段:
public String getLastRun(String failedDate, String failedTime)
{
}String failedDate, String failedTime是以上述格式从DB获得的Date和Time。
现在的问题是,我需要计算的天数,小时,时间,秒从那个日期和时间作为输入。
所以,如果当前日期是Thursday 02-November-2022,时间是11:51:1 PM,我可以计算出经过的天数、小时、时间、秒数。
输出:Last service failed 30 Days 12 hours 55 minutes 45 seconds类型的输出,计算给定的日期和时间字段作为当前日期和时间的输入?
到目前为止,我已经将这个Date和Time作为Java类中Wednesday 02-October-2022和11:51:1 PM的这种格式的输入,但我仍然不确定:
我检查了以下链接:带有本地日期的Link1、Link2,但这些链接都没有帮助我动态获取给定日期和时间格式中的天数、小时、时间、秒数。
我甚至尝试过使用SimpleDateFormat,如提到的这里,但无法获得这种格式。
任何要开始的示例或指针都会有帮助。
请注意:时区是IST亚洲/加尔各答
发布于 2022-11-02 19:33:57
使用LocalDate将日期解析为DateTimeFormatter。这已经在Stack溢出上讨论过很多次了。
使用LocalTime将一天中的时间解析为DateTimeFormatter。这已经在Stack溢出上讨论过很多次了。
指定您的预定时区。
ZoneId zone = ZoneId.of( "Asia/Kolkata" ) ;合并。
ZonedDateTime zdt = ZonedDateTime.of( date , time , zone ) ;通过提取Instant调整到UTC。
Instant then = zdt.toInstant () ;使用Duration计算24小时长的“天”(而不是日历日)、小时、分钟、秒和纳诺的运行时间。
Duration duration = Duration.between ( then , Instant.now() ) ;理想的解决方案是教育您的数据发布者使用标准的ISO 8601格式。
发布于 2022-11-02 21:34:20
你的步骤如下:
LocalDate将日期字符串解析为DateTimeFormatter。LocalTime将时间字符串解析为DateTimeFormatter。LocalDateTime和LocalTime实例创建一个LocalDate实例。Duration和当前的日期时间之间查找LocalDateTime。Duration中获取天、小时、分钟、秒。Demo
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(getLastRun("Wednesday 05-October-2022", "11:51:1 PM"));
}
public static String getLastRun(String failedDate, String failedTime) {
LocalDateTime givenDateTime = LocalDateTime.of(
LocalDate.parse(failedDate, DateTimeFormatter.ofPattern("EEEE dd-MMMM-uuuu", Locale.ENGLISH)),
LocalTime.parse(failedTime, DateTimeFormatter.ofPattern("h:m:s a", Locale.ENGLISH)));
LocalDateTime now = LocalDateTime.now();
Duration duration = givenDateTime.isAfter(now) ? Duration.between(now, givenDateTime)
: Duration.between(givenDateTime, now);
return String.format("Last service failed %d Days %d hours %d minutes %d seconds",
duration.toDaysPart(), duration.toHoursPart(), duration.toMinutesPart(), duration.toSecondsPart());
}
}输出
Last service failed 27 Days 21 hours 27 minutes 49 secondshttps://stackoverflow.com/questions/74294625
复制相似问题