Time example: use tm_wday instead of manually calculating day-of-week. Added comment regarding UTC/localtime().

This commit is contained in:
yellows8 2018-02-22 17:53:41 -05:00
parent fff86cfc8d
commit 340148ca40

View File

@ -8,37 +8,6 @@ const char* const months[12] = {"January", "February", "March", "April", "May",
const char* const weekDays[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
const u16 daysAtStartOfMonthLUT[12] =
{
0 % 7, //january 31
31 % 7, //february 28+1(leap year)
59 % 7, //march 31
90 % 7, //april 30
120 % 7, //may 31
151 % 7, //june 30
181 % 7, //july 31
212 % 7, //august 31
243 % 7, //september 30
273 % 7, //october 31
304 % 7, //november 30
334 % 7 //december 31
};
static inline bool isLeapYear(int year)
{
return (year%4) == 0 && !((year%100) == 0 && (year%400) != 0);
}
static inline int getDayOfWeek(int day, int month, int year)
{
//http://en.wikipedia.org/wiki/Calculating_the_day_of_the_week
day += 2*(3-((year/100)%4));
year %= 100;
day += year + (year/4);
day += daysAtStartOfMonthLUT[month] - (isLeapYear(year) && (month <= 1));
return day % 7;
}
int main(int argc, char **argv)
{
gfxInitDefault();
@ -59,7 +28,8 @@ int main(int argc, char **argv)
//Print current time
time_t unixTime = time(NULL);
struct tm* timeStruct = gmtime((const time_t *)&unixTime);
struct tm* timeStruct = gmtime((const time_t *)&unixTime);//Gets UTC time. Currently localtime() will also return UTC (timezones not supported).
int hours = timeStruct->tm_hour;
int minutes = timeStruct->tm_min;
@ -67,9 +37,10 @@ int main(int argc, char **argv)
int day = timeStruct->tm_mday;
int month = timeStruct->tm_mon;
int year = timeStruct->tm_year +1900;
int wday = timeStruct->tm_wday;
printf("\x1b[1;1H%02i:%02i:%02i", hours, minutes, seconds);
printf("\n%s %s %i %i", weekDays[getDayOfWeek(day, month, year)], months[month], day, year);
printf("\n%s %s %i %i", weekDays[wday], months[month], day, year);
gfxFlushBuffers();
gfxSwapBuffers();