Neat App
Posted: Sun Mar 09, 2008 12:01 am
I was thinking about time, earlier, and wondered how many seconds had passed since 0001-01-01 00:00:00...and, well, you can imagine what I came up with.
It seems to calculate it fairly accurately...so, woot.
Took me a few minutes to figure out why MinGW was failing miserably with %lld.
This is somewhat related: http://theoryuniverse.com/theory/?p=4
Code: Select all
/* by [email protected] */
#include <stdio.h>
#include <time.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#define Sleep usleep
#endif
#define CENTURY 20
#define YEAR 8
#define MSG "Seconds since 0001-01-01 00:00:00"
int months[] = {
31,
31 + 28,
31 + 28 + 31,
31 + 28 + 31 + 30,
31 + 28 + 31 + 30 + 31,
31 + 28 + 31 + 30 + 31 + 30,
31 + 28 + 31 + 30 + 31 + 30 + 31,
31 + 28 + 31 + 30 + 31 + 30 + 31 + 31,
31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30,
31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31,
31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30,
31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31
}, months2[12];
unsigned long long int Calculate(int print)
{
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
int month = timeinfo->tm_mon;
int day = day = timeinfo->tm_mday, hour = timeinfo->tm_hour;
int minute = timeinfo->tm_min, second = timeinfo->tm_sec;
int yyyy = (CENTURY * 100) + YEAR;
int leap = ((yyyy % 4 == 0) && (yyyy % 100 != 0) || (yyyy % 400 == 0));
if(leap) {
int idx;
for(idx = 0; idx < sizeof(months) / sizeof(months[0]); idx++) {
months2[idx] = months[idx] + 1;
}
}
unsigned long long int result = ((yyyy * (leap ? 366 : 365)) +
months2[month]) + day;
result = (result * 24) + hour;
result = (result * 60) + minute;
result = (result * 60) + second;
if(print) {
printf("Century: %d\nYear: %d\nMonth: %d\nDay: %d\n", CENTURY, YEAR,
month, day);
printf("Hour: %d\nMinute: %d\nSecond: %d\n", hour, minute, second);
printf("Year (centurized): %d\n", yyyy);
printf("Is leap year? %d\n", leap);
}
return result;
}
int main()
{
int print = 1;
for(; ; ) {
unsigned long long int value = Calculate(print);
print = 0;
printf("\r");
#ifdef MINGW
printf("%s: %I64u", MSG, value);
#else
printf("%s: %lld", MSG, value);
#endif
fflush(stdin);
Sleep(1);
}
return 0;
}
Took me a few minutes to figure out why MinGW was failing miserably with %lld.
This is somewhat related: http://theoryuniverse.com/theory/?p=4