Home > Software engineering >  How to calculate nanoseconds from 1800
How to calculate nanoseconds from 1800

Time:06-10

I'm trying to calculate the number of nano seconds that passed from: 11-Nov-1831 00:00:00.00

to a given date.

I tried to use alot of packages but none of them succed in the mission (the closest was Instant)

What's the best way to achive this mission?

CodePudding user response:

Instant is still the best option, but you may need some helper objects.

For instance, to create the start date (replace the Z with a different time zone or offset as needed):

Instant start = Instant.parse("1831-11-11T00:00:00Z");

Then take the given date. You can parse it, or use conversion methods. For instance, if you have a LocalDateTime (use a different ZoneId or ZoneOffset as needed):

LocalDateTime localDateTime = LocalDateTime.parse("2022-06-09T20:56");
Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();

Now get a duration:

Duration duration = Duration.between(start, instant);
long nanos = duration.toNanos();

CodePudding user response:

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static void main(String[] args) throws Exception {
        long nowInMilliSeconds = System.currentTimeMillis();
        
        Date baseDate = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss").parse("11-Nov-1831 00:00:00.00");
        long baseDateInMilliSeconds = baseDate.getTime();
        
        long nanoSecondsSinceBaseDate = (nowInMilliSeconds - baseDateInMilliSeconds)* 1000000;
        //The (nowInMilliSeconds - baseDateInMilliSeconds) is in milli seconds thus multiplied by 1000000 that gives difference in nano seconds
        System.out.println(nanoSecondsSinceBaseDate);
    }
}

Each day in nano seconds: 24*3600*1000000000

Each year in nano seconds: 365*24*3600*1000000000

Compute approximate expected result using these formulas and compare with method's result to check the output

  • Related