Home > Net >  Get 25 hours back time in epoch using java 8 date time
Get 25 hours back time in epoch using java 8 date time

Time:10-03

i want to get the 25 hours in miliseconds i.e. 90000000 (25 hours in ms) is there any way i can calculate dynamically using Java 8 Date and Time api ? i am trying like below:

LocalDate.now().minusHours(25).toEpochDay()

but seems compilation error::

The method minusHours(int) is undefined for the type LocalDate

CodePudding user response:

The following gives you 25 hours converted into milliseconds:

Duration.ofHours(25).toMillis()

If you want an Instant behind the Unix epoch, you can subtract this duration from Instant.EPOCH using Instant.EPOCH.minus.

Demo:

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

public class Solution {
    public static void main(String[] args) {
        Duration duration = Duration.ofHours(25);
        System.out.println(duration.toMillis());

        // Instant 25 hours before Unix Epoch
        System.out.println(Instant.EPOCH.minus(duration));

        // *** Some other useful information ***
        // Unix Epoch is zero millisecond. Therefore, any number of millis behind this
        // is simply in -ve of this number
        System.out.println(Instant.EPOCH.toEpochMilli());
        System.out.println(Instant.EPOCH.minus(duration).toEpochMilli());

        // Instant and LocalTime in Stockholm 25 hours ago
        System.out.println(Instant.now().minus(duration));
        System.out.println(Instant.now().minus(duration).toEpochMilli());
        System.out.println(LocalDateTime.now(ZoneId.of("Europe/Stockholm")).minus(duration));
    }
}

Output at this moment:

90000000
1969-12-30T23:00:00Z
0
-90000000
2022-10-01T15:49:56.515750Z
1664639396515
2022-10-01T17:49:56.541261

Learn more about the the modern date-time API from Trail: Date Time.

CodePudding user response:

First you seemed to ask for the moment of twenty-five hours after the first moment of 1970 as seen with an offset of zero hours-minutes-seconds.

Duration d = Duration.ofHours( 25 ) ;
Instant instant = Instant.EPOCH.plus( d );

See this code run at Ideone.com.

instant.toString() = 1970-01-02T01:00:00Z

Then you changed your Question to ask how to calculate the number of milliseconds on 25 hours.

Duration d = Duration.ofHours( 25 ) ;
long milliseconds = d.toMillis() ; 

The result is ninety million.

90000000

  • Related