I want nanoTime() of last 24 hours. long currentDate=System.nanoTime(); how to find nanoTime by subtracting 24 hours? Is it possible to get nanoTime from Date date = new Date()?
1 Answer
System.nanoTime() cannot be used for current time. It is “is not related to any other notion of system or wall-clock time”, as the docs say. This also means that getting a compatible nano time from a Date would not make sense.
Instead use java.time.Instant for your times. Instant.now() gives you the current time, and from Java 9 it has a very high resolution on most platforms (microseconds on my Mac, I believe it’s just a good as nanoTime). Then use for example yourInstant.minus(1, ChronoUnit.DAYS) or yourInstant.minus(Duration.ofHours(24)).
I need to store long value in database.
Edit: I’d prefer to store the Instant as such into the database, or if that’s not possible, then its string representation as you get it from its toString method (the Instant class can parse this string back into an Instant). Since I understand that you’re required to save a long value: This will be possible until 2262-04-11T23:47:16.854775807Z, the next more than 200 years. If this is good enough, here’s how to get nanoseconds since the epoch as a long value from an Instant:
Instant instantNow = Instant.now(); long now = Math.addExact( Math.multiplyExact(instantNow.getEpochSecond(), 1_000_000_000), instantNow.getNano()); The point in using addExact and multiplyExact from the Math class rather than plain + and * is you will be notified in case of overflow, that is, in case the value doesn’t fit into a long.
is it possible to convert date to Instant, as we have search by date function on UI[?]
To convert a date (like December 25, 2017) to an Instant you need to decide a time zone for the conversion because it is never the same date everywhere on Earth. For example:
ZoneId zone = ZoneId.of("Europe/Brussels"); LocalDate date = LocalDate.of(2017, Month.DECEMBER, 25); Instant asInstant = date.atStartOfDay(zone).toInstant(); To answer your original question (doubting that you can use it), to subtract 24 hours from System.nanoTime():
long nanoYesterday = System.nanoTime() - TimeUnit.DAYS.toNanos(1); 3 Comments
long? If it's the latter, why not just use System.currentTimeMills()? (Or equivalently Instant.toEpochMilli()?)
nanoTimeif you want to do that I guess?System.nanoTime() - (long) (8.64e+13);No idea what you would use that for though.new java.util.Date().getTime(), which is accurate to milliseconds, and simply subtract 24 hours worth of milliseconds (24*60*60*1000L) from it?