Skip to content

Instantly share code, notes, and snippets.

@PhirePhly
Created October 14, 2016 01:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PhirePhly/fe30cdba68cc2241a4326a4c077963cb to your computer and use it in GitHub Desktop.
Save PhirePhly/fe30cdba68cc2241a4326a4c077963cb to your computer and use it in GitHub Desktop.
Calculate the local day of the week from Unix time and time zone offset
#include <stdio.h>
#include <time.h>
// Calculate the current day of the week as an integer
// now - Unix timestamp like that from time(NULL)
// tz_offset - Number of hours off from UTC; i.e. PST = -8
// Return value: Sunday=0, Monday=1, ... Saturday=6
int dayofweek(time_t now, int tz_offset) {
// Calculate number of seconds since midnight 1 Jan 1970 local time
time_t localtime = now + (tz_offset * 60 * 60);
// Convert to number of days since 1 Jan 1970
int days_since_epoch = localtime / 86400;
// 1 Jan 1970 was a Thursday, so add 4 so Sunday is day 0, and mod 7
int day_of_week = (days_since_epoch + 4) % 7;
return day_of_week;
}
int main() {
time_t now = time(NULL);
printf("Current day of week: %i\n", dayofweek(now, -7));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment