Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the day of the week based on unix time

Tags:

date

math

I know that there are functions/classes in most programming languages to do that, but I would like to know the calculation.

So: How do I get from the unix time in seconds to a day-number (e.g. 0 for Sunday, 1 for Monday etc.)?

Thanks in advance. BTW: this is my first post on Stack Overflow.

like image 561
Jermano Avatar asked Dec 14 '22 07:12

Jermano


1 Answers

The problem you ask is reasonably easy, compared to how ridiculously complicated other date/time functions can be (e.g. Zeller's congruence).

  1. Unix time is defined as the number of seconds elapsed after January 1, 1970, at 00:00 (midnight) UTC.

  2. You can look up a calendar to find that 1970-01-01 was a Thursday. There are 24 * 60 * 60 = 86400 seconds in a day.

  3. Therefore values 0 to 86399 are Thursday, 86400 to 172799 are Friday, 172800 to 259199 are Saturday, etc. These are blocks of 86400 seconds aligned at 0.

  4. Suppose T is your Unix timestamp. Then floor(T / 86400) tells you the number of days after 1970-01-01. 0 = Thursday January 1st; 1 = Friday January 2nd; 2 = Saturday January 3rd; etc.

  5. Add 4 and modulo 7. Now 0 → 4; 1 → 5; 2 → 6; 3 → 0; 4 → 1; 5 → 2; 6 → 3; 7 → 4; 8 → 5; 9 → 6; 10 → 0; etc. This is your final answer.

  6. In summary: day of week = (floor(T / 86400) + 4) mod 7.

  7. (This assumes that you want the day of week in UTC. If you want to calculate it for another time zone, you need to perform some addition or subtraction of hours and minutes on T first.)

like image 133
Nayuki Avatar answered Jan 07 '23 12:01

Nayuki