/* date.c - Don Yang (uguu.org) Date functions. 05/27/12 */ #include #include #include /* Moon phase labels for GetMoonPhase */ static const char *label[8] = { "new moon", "waxing crescent", "first quarter", "waxing gibbous", "full moon", "waning gibbous", "last quarter", "waning crescent" }; /* Return moon phase for a particular timestamp */ static int GetMoonPhase(int t) { const int synodic_period = (int)(29.530589 * 86400); t -= 434928; return ((t % synodic_period) * 8) / synodic_period; } int main(int argc, char **argv) { struct tm t; time_t s; int i; /* Initialize time info */ s = time(NULL); memcpy(&t, localtime(&s), sizeof(t)); printf("%04d-%02d-%02d %02d:%02d:%02d\n", t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec); t.tm_hour = t.tm_min = t.tm_sec = 0; if( argc == 1 ) { /* Get moon phase for today */ s = mktime(&t); printf("Today=%04d-%02d-%02d: %d %s\n", t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, (int)s, label[GetMoonPhase((int)s)]); return 0; } for(i = 1; i < argc; i++) { /* Get moon phase for dates specified on command line arguments */ if( sscanf(argv[i], "%d-%d-%d", &t.tm_year, &t.tm_mon, &t.tm_mday) == 3 ) { printf("%04d-%02d-%02d: ", t.tm_year, t.tm_mon, t.tm_mday); t.tm_year -= 1900; t.tm_mon--; s = mktime(&t); if( s == (time_t)-1 ) { puts("invalid"); continue; } printf("%d %s\n", (int)s, label[GetMoonPhase((int)s)]); } } return 0; }