Поиск Я не нашел ни хорошего решения для синтаксического анализа строки метки времени RFC3339 в редактируемый формат, ни способа вычислить разницу к текущему моменту.
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Given date-time
LocalDateTime ldt = ZonedDateTime
.parse("2020-06-19T15:32:25.528Z",
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz").withZone(ZoneId.systemDefault()))
.toLocalDateTime();
// Get the duration between the given date-time and now
Duration duration = Duration.between(ldt, LocalDateTime.now(ZoneId.systemDefault()));
// Get hours, minutes, seconds from the Duration object
System.out.printf("%d hours %d minutes %d seconds%n", duration.toHoursPart(), duration.toMinutesPart(),
duration.toSecondsPart());
}
}
Вывод:
3 hours 3 minutes 43 seconds
[Обновление]
Обратите внимание, что Duration#toXXXXXPart()
например, Duration#toHoursPart()
был введен с Java -9. Если вы используете Java -8, вы можете использовать расчет, показанный ниже:
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Given date-time
LocalDateTime ldt = ZonedDateTime
.parse("2020-06-19T15:32:25.528Z",
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz").withZone(ZoneId.systemDefault()))
.toLocalDateTime();
// Get the duration between the given date-time and now
Duration duration = Duration.between(ldt, LocalDateTime.now(ZoneId.systemDefault()));
// Get hours, minutes, seconds from the Duration object
System.out.printf("%d hours %d minutes %d seconds%n", duration.toHoursPart(), duration.toMinutesPart(),
duration.toSecondsPart());
// For Java-8
long hours = duration.toHours();
int minutes = (int) ((duration.getSeconds() % (60 * 60)) / 60);
int seconds = (int) (duration.getSeconds() % 60);
System.out.printf("%d hours %d minutes %d seconds%n", hours, minutes, seconds);
}
}
[Другое обновление] Предоставлено Ole VV
import java.time.Duration;
import java.time.Instant;
public class Main {
public static void main(String[] args) {
// Given date-time
Instant instant = Instant.parse("2020-06-19T15:32:25.528Z");
// Get the duration between the given date-time and now
Duration duration = Duration.between(instant, Instant.now());
// Get hours, minutes, seconds from the Duration object
System.out.printf("%d hours %d minutes %d seconds%n", duration.toHoursPart(), duration.toMinutesPart(),
duration.toSecondsPart());
}
}