Search code examples
javascalautcepochaerospike

In Java/Scala how to get specific UTC date in seconds with minimal amount of code/ in most elegant way?


To be more specific I need:

// seconds from Jan 1 2010
val currentAerospikeTime = (new Date().getTime - new Date(110, 0, 1).getTime)/1000;

But it uses the deprecated Date constructor, so I get a warning. But in Scala there is no way to turn off the warning for a single line (and I don't want to turn it off completely). So how can I rewrite it, to make it terser and let it compile without the warning?

Maybe I'm missing something but I can't find a short way to do it, neither with the Java 8 API nor with the Joda library (didn't reserch it thoroughly, but I don't want to add the library just for this line either).


Solution

  • How about using ChronoUnit#between to work this out, e.g.:

    ChronoUnit.SECONDS.between(
        LocalDate.of(2010, 1, 1).atStartOfDay(ZoneId.of("Z")), 
        ZonedDateTime.now());
    

    Or alternatively, really terse:

    (System.currentTimeMillis() - 1262304000000L) / 1000;