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.
The problem you ask is reasonably easy, compared to how ridiculously complicated other date/time functions can be (e.g. Zeller's congruence).
Unix time is defined as the number of seconds elapsed after January 1, 1970, at 00:00 (midnight) UTC.
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.
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.
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.
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.
In summary: day of week = (floor(T / 86400) + 4) mod 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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With