-1

I have a month July 2022 for example, I want get epoch milis for the first day of the month

1st July 2022 at midnight.

from the month I was able to get the 1st July 2022, but how to convert it into epoch milis for 1st July 22 midnight

    val datey = "July/2020"
    val dateFormaty = DateTimeFormatter.ofPattern("MMMM/yyyy")
    val yearMonthy = YearMonth.parse(datey, dateFormaty)
    val parsedDatey = yearMonthy.atDay(1)

I get 2022-07-01 for parsedDate, I want to get the date time for this date in epoch milis

Thanks R

BRDroid
  • 3,920
  • 8
  • 65
  • 143
  • Have you [read the documentation](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#toEpochDay--) ? Perhaps `parsedDatey.toEpochDay()` is the thing you're looking for? Watch out for this part of the documentation **This class does not store or represent a time or time-zone. Instead, it is a description of the date, as used for birthdays. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.** – Shark Jul 27 '22 at 14:38
  • I tried that but it gave me a 1970 date, so that did not work for me – BRDroid Jul 27 '22 at 15:02
  • Does this answer your question? [Convert java.time.LocalDate into java.util.Date type](https://stackoverflow.com/questions/22929237/convert-java-time-localdate-into-java-util-date-type) – Shark Jul 28 '22 at 12:57
  • "how to convert it into epoch milis for 1st July 22 midnight" your example literally never mentions nor provides the midnight part to the Date. – Shark Jul 28 '22 at 13:05

1 Answers1

0

Like I mentioned, LocalDate does not actually store any time information whatsoever, so transforming it to epoch isn't possible. Technically. Yet it is with some possible inacuracies.

How about something like this:

make the following extension function

fun LocalDate.toDate(): Date = Date.from(this.atStartOfDay(ZoneId.systemDefault()).toInstant())

Note that it uses the system default timezone for this, to provide the necessary information.

then just use it.

val myDate = myLocalDate.toDate()

which would in your case, be parsedDatey.toDate()

But, we don't really even need the Date here. Lets avoid casting the LocalDate to Date then getting the epoch milli from there, and just do it from the provided Instant instead.

So the real answer to your question is this:

fun LocalDate.getEpochMillis(): long = this.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()

// call this in your parsing method you posted
parsedDatey.getEpochMillis()
Shark
  • 6,513
  • 3
  • 28
  • 50