I'm trying to calculate the day of week from a seconds since epoch timestamp. From time.h
I can use gmtime()
, but this increases the program with 1.3kB, probably because gmtime()
also calculates the date.
So, I'm wondering what would be wrong about using something like:
(timestamp / (24*3600)) % 7
The only thing I could think of is leap seconds, such that something like 00:00:02 could be classified as the wrong day.
edit This is for embedded programming, 1.3kB is a substantial part of the 64kB program/firmware. Furthermore, I'm not expecting to do anything with timezones or dates after this.
what would be wrong about using something like: (?)
(timestamp / (24*3600)) % 7
Not much wrong with the above except you have not specified the day of the week the epoch began (e.g. Thursday) nor the day of the week the week begins on (e.g. Monday). See 8601 for a deeper discusison on the first day of the week. Also watch out for computations like 24*3600
that with 16-bit int/unsigned
lead to troubles.
Example: Let us say the epoch began on day-of-the-week number 3 (Monday:0. Thursday:3). This takes care of 2 issues at once: day of the week of the epoch and the first day of the week as only the positive difference needs to be coded.
#define EPOCH_DOW 3
#define SECS_PER_DAY 86400
dow = ((timestamp / SECS_PER_DAY) + EPOCH_DOW) % 7;
If timestamp
is a signed type, append the following to insure a result in the [0...6]
range.
dow = (dow + 7) % 7;
// or
if (dow < 0) dow += 7;
I doubt leap seconds are used in your application. If they are, the task is far more complicated as code then needs to deal with not only with a more complex calculation, but how to receive updates of the next scheduled leap-seconds - they occur irregularly.
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