1

I would like to get the date & time now and from that do the following: (i) set the month to the first and (ii) zero out everything after the month (iii) calculate the date 1 year and 1 month back and How can I do this using the new Date-Time API of Java?

jshell> import java.time.LocalDateTime;
jshell> import java.time.ZoneId;

jshell> LocalDateTime.now(ZoneId.of("GMT"));
$3 ==> 2021-01-29T01:41:14.273303

jshell> $3.minusYears(1).minusMonths(1).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
$4 ==> 2019-12-01T00:00:00.273303

jshell> $4.atZone(ZoneId.of("GMT"));
$5 ==> 2019-12-01T00:00:00.273303Z[GMT]

jshell> $5.toInstant().toEpochMilli();
$6 ==> 1575158400273

However, what I want is the equivalent of the below:

$4 ==> 2019-12-01T00:00:00.000000

Any ideas on how to do it? Will really appreciate the help.

Jared
  • 73
  • 6
  • 2
    Use `LocalDate` not `LocalDateTime`? – Scary Wombat Jan 29 '21 at 02:00
  • 2
    `LocalDate.now().atStartOfDay()` with all the other adjustments you want there too? – BeUndead Jan 29 '21 at 02:03
  • 1
    **`LocalDateTime` is exactly the *wrong* class** to use here. If you want to track moments, points on the timeline, do *not* use that class. Use `Instant`, `OffsetDateTime`, or `ZonedDateTime`. This has been covered many many many times already on Stack Overflow. Search to learn more. And search thoroughly before posting. – Basil Bourque Jan 29 '21 at 07:12
  • 1
    If you want the count of milliseconds between the first moment of 1970 as seen in UTC and the first moment of a year ago from today as seen in UTC: `LocalDate.now( ZoneOffset.UTC ).minusYears( 1 ).atStartOfDay( ZoneOffset.UTC ).toInstant().toEpochMilli()`. See [this code run live at IdeOne.com](https://ideone.com/nnvW7F). – Basil Bourque Jan 29 '21 at 07:20
  • I suggest `YearMonth.now(ZoneOffset.UTC).minusYears(1).minusMonths(1).atDay(1).atStartOfDay(ZoneOffset.UTC)`. It yields `2019-12-01T00:00Z`. – Ole V.V. Jan 30 '21 at 13:50

0 Answers0