levtatarov
levtatarov

Reputation: 1712

Java: how to calculate number of days from the beginning of time (with time zones)

I want to calculate the number of days from the "beginning of time" to a current date. This could be easily achieved with a simple calculation (timestamp / 24 / 60 / 60 / 1000 = daysFromBeginningOfTime) but the twist is that i need to be aware of time zones as well. The timestamp is the same everywhere in the world but when you parse it with the proper time zone then it reflects the differences between locations so using just the timestamp doesn't work and i don't want to handle all the time zone transitions myself.

Example: if it's 23:30 in London and the day number is 18843 then in Amsterdam it's 0:30 and the day number should be 18844.

I looked at joda.time but didn't really find what i was looking for. Anyone have any ideas?

Upvotes: 0

Views: 546

Answers (2)

Ingo
Ingo

Reputation: 36339

The problem appears due to a wrong initial assumption, I think.

The argument the OP makes in his example is not correct. No matter what the clock shows in London or Amsterdam, the time difference to the start of the epoch is - at every point of time - independent of where you are in the world.

Hence, the solution is to parse a given input date to an UTC timestamp and proceed as before.

Upvotes: 1

Stephen C
Stephen C

Reputation: 718826

(Ignoring the point that zero is not "the beginning of time" ... and that the actual time point for the beginning of time is probably unknowable ...)

Here's how to calculate the number of days since "the local-time UNIX epoch in a given timezone"1.

  1. Get hold of the object that represents the local timezone.
  2. Get the timezone's offset from the object
  3. Convert it to milliseconds and add it to the current UTC time.
  4. Calculate the day number as before.

1 - ... whatever that means.

Upvotes: 1

Related Questions