-3

Edit:

lets say I have the date 11.11.2016 for what I want the Unix timestamp.

At the moment I just use

 final int start = (int) ((System.currentTimeMillis() - 24 * 60 * 60 * 1000 * 5) / 1000L);

for 10.11.2016 it would be

     final int start = (int) ((System.currentTimeMillis() - 24 * 60 * 60 * 1000 * 6) / 1000L);

But it looks somehow so basic :)

Is there maybe a better solution? I couldn't find any function in Date nor LocalTime.

Thanks!

PowerFlower
  • 1,619
  • 4
  • 18
  • 27
  • 1
    "and substract days"? What exactly do you want to do? [This](http://stackoverflow.com/questions/7784421/getting-unix-timestamp-from-date)? [Or this](http://stackoverflow.com/a/20906602/1743880)? – Tunaki Nov 16 '16 at 21:53
  • There is [`Instant#toEpochMilli`](https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#toEpochMilli--) and [`Instant#getEpochSecond`](https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#getEpochSecond--). – bradimus Nov 16 '16 at 21:54
  • 1
    There is a basic type mismatch here: `10.05.2016` is a day-long period; a unix timestamp is roughly an instant in time (actually, it's a second-long period). You can't convert a `10.05.2016` to a unix timestamp without specifying 1) a time zone; 2) a time of day. – Andy Turner Nov 16 '16 at 22:01
  • @PowerFlower Please edit your question and title to clarify. And almost certainly this is a duplicate as we have thousands of existing questions and answers on handling date-time in Java. Please search before posting, and close/delete your Question if it is a duplicate. – Basil Bourque Nov 16 '16 at 22:20
  • 1
    A calendar date is not a unix timestamp. Two totally different concepts! While you can convert an `Instant` to a long-value as elapsed seconds since Unix epoch, you can convert a `LocalDate` to a long using its method [toEpochDay](http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#toEpochDay--) – Meno Hochschild Nov 16 '16 at 22:31

1 Answers1

4

It only makes sense to convert a "date" to epoch seconds if you specify a time of day and a time zone that you want the epoch seconds for.

Otherwise, the conversion is undefined, because a "date" is a 24-hour period (usually) in a specific timezone, whereas a unix timestamp is a number of seconds since 1970-1-1 00:00:00 UTC.

LocalDate.of(2016, 5, 10)

    // e.g. LocalTime.of(12, 0) or .atStartOfDay()
    // - *not* midnight, in general, since this does not always exist.
    .atTime(someLocalTime)

    // e.g. ZoneId.of("UTC")
    .atZone(someTimeZoneId)

    .toEpochSecond();
Andy Turner
  • 137,514
  • 11
  • 162
  • 243