Appropriate way to set a duration in Java
What is the appropriate way to set a duration in Java with standard Java libs? Date()? Cal开发者_运维知识库endar()? Example?
Thanks & Cheers ER
There is a de-facto standard for Java Date & time - JodaTime. It has Duration
. The JodaTime API is considered far better than Date
and Calendar
.
Of course, you can also store the duration in a long
- the milliseconds.
Using Java-8 standard library
java.time.Duration
is modelled on ISO-8601 standards and was introduced as part of JSR-310 implementation.
A quick demo:
import java.time.Duration;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
System.out.println(Duration.ofNanos(1234567890));
System.out.println(Duration.ofMillis(123456789));
System.out.println(Duration.ofSeconds(12345678));
System.out.println(Duration.ofMinutes(1234567));
System.out.println(Duration.ofHours(123456));
System.out.println(Duration.ofDays(12345));
System.out.println(Duration.between(LocalTime.of(1, 2, 3), LocalTime.of(4, 5, 6)));
}
}
Output:
PT1.23456789S
PT34H17M36.789S
PT3429H21M18S
PT20576H7M
PT123456H
PT296280H
PT3H3M3S
Learn about the modern date-time API from Trail: Date Time.
精彩评论