Java 8 date-time: get start of day from ZonedDateTime

Updated for sake of correction: In most cases yes the same, see following example for Brazil when switching from winter to summer time: ZonedDateTime zdt = ZonedDateTime.of(2015, 10, 18, 0, 30, 0, 0, ZoneId.of(“America/Sao_Paulo”)); // switch to summer time ZonedDateTime zdt1 = zdt.truncatedTo(ChronoUnit.DAYS); ZonedDateTime zdt2 = zdt.toLocalDate().atStartOfDay(zdt.getZone()); System.out.println(zdt); // 2015-10-18T01:30-02:00[America/Sao_Paulo] System.out.println(zdt1); // 2015-10-18T01:00-02:00[America/Sao_Paulo] System.out.println(zdt2); // … Read more

Why can’t I get a duration in minutes or hours in java.time?

“Why was it implemented that way?” Other answers deal with the toXxx() methods that allow the hours/minutes to be queried. I’ll try to deal with the why. The TemporalAmount interface and get(TemporalUnit) method was added fairly late in the process. I personally was not entirely convinced that we had enough evidence of the right way … Read more

What does ‘PT’ prefix stand for in Duration?

As can be found on the page Jesper linked to (ISO-8601 – Data elements and interchange formats – Information interchange – Representation of dates and times) P is the duration designator (for period) placed at the start of the duration representation. Y is the year designator that follows the value for the number of years. … Read more

long timestamp to LocalDateTime

You need to pass timestamp in milliseconds: long test_timestamp = 1499070300000L; LocalDateTime triggerTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(test_timestamp), TimeZone.getDefault().toZoneId()); System.out.println(triggerTime); Result: 2017-07-03T10:25 Or use ofEpochSecond instead: long test_timestamp = 1499070300L; LocalDateTime triggerTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(test_timestamp), TimeZone.getDefault().toZoneId()); System.out.println(triggerTime); Result: 2017-07-03T10:25

How can I mock java.time.LocalDate.now()

In your code, replace LocalDate.now() with LocalDate.now(clock);. You can then pass Clock.systemDefaultZone() for production and a fixed clock for testing. This is an example : First, inject the Clock. If you are using spring boot just do a : @Bean public Clock clock() { return Clock.systemDefaultZone(); } Second, call LocalDate.now(clock) in your code : @Component … Read more

How to convert from Instant to LocalDate

Java 9+ LocalDate.ofInstant(…) arrived in Java 9. Instant instant = Instant.parse(“2020-01-23T00:00:00Z”); ZoneId zone = ZoneId.of(“America/Edmonton”); LocalDate date = LocalDate.ofInstant(instant, zone); See code run live at IdeOne.com. Notice the date is 22nd rather than 23rd as that time zone uses an offset several hours before UTC. 2020-01-22 Java 8 If you are using Java 8, then … Read more