-1

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?

emal
  • 11
  • 5
  • Can you compute the fixed number of nanoseconds from 11-Nov-1831 to 01-Jan-1970 and just add that offset to your normal timestamps? – Mad Physicist Jun 09 '22 at 18:57
  • That's a good solution but if the start date will change, we will need to calcuate it again. – emal Jun 09 '22 at 19:17
  • Why that particular start date, out of curiosity? – Mad Physicist Jun 09 '22 at 19:22
  • No one knows, but I'll try to find out :D – emal Jun 09 '22 at 19:47
  • 11-Nov-1831 00:00:00.00 in which time zone? Do you have trustworthy time zone data for that time zone this far back? I believe that it’s from before GMT came into use (outside UK at least). – Ole V.V. Jun 10 '22 at 14:59
  • Nanoseconds since the date you mention can be held in a `long` until year 2124, so 100 years from now. A potential new “year 2000 problem” might worry me just a bit. – Ole V.V. Jun 12 '22 at 16:42
  • i used System default timezone – emal Jun 13 '22 at 12:17

1 Answers1

1

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();
Rob Spoor
  • 6,186
  • 1
  • 19
  • 20
  • I think that the number we calculate is to big, the result of : Instant start = Instant.parse("1831-11-11T00:00:00.00Z"); LocalDateTime localDateTime = LocalDateTime.parse("2007-12-03T10:15:30.00"); is 5555981730000000000 which not make sense. There is a way to solve it with this tools? – emal Jun 09 '22 at 19:39
  • @emal The number is not too big. `Duration#toNanos` is documented as throwing an exception if the result would be too long. The maximum of a `long` is enough for about 292 years worth of nanoseconds. And there are indeed 5,555,988,930,000,000,000 nanoseconds between 1831-11-11T00:00:00Z and 2007-12-03T10:15:30Z. See all this math [at Ideone.com](https://ideone.com/6PaZL4). Note also that `LocalDateTime` is the wrong type to use here. – Basil Bourque Jun 10 '22 at 03:55
  • @BasilBourque you're right about `LocalDateTime`, I used it as an example. The instant comes from the `ZonedDateTime` that was created by applying the `ZoneId` to the `LocalDateTime`. – Rob Spoor Jun 10 '22 at 12:29