date.c revision c0e56edaf256adb6c60c5a052525a1ffbb927901
1/* vi: set sw=4 ts=4: 2 * 3 * date.c - set/get the date 4 * 5 * Copyright 2012 Andre Renaud <andre@bluewatersys.com> 6 * 7 * See http://opengroup.org/onlinepubs/9699919799/utilities/date.html 8 9USE_DATE(NEWTOY(date, "r:u", TOYFLAG_BIN)) 10 11config DATE 12 bool "date" 13 default y 14 help 15 usage: date [-u] [-r file] [+format] | mmddhhmm[[cc]yy] 16 17 Set/get the current date/time 18*/ 19 20#define FOR_date 21#include "toys.h" 22 23GLOBALS( 24 char *file; 25) 26 27void date_main(void) 28{ 29 const char *format_string = "%a %b %e %H:%M:%S %Z %Y"; 30 time_t now = time(NULL); 31 struct tm tm; 32 33 if (TT.file) { 34 struct stat st; 35 36 xstat(TT.file, &st); 37 now = st.st_mtim.tv_sec; 38 } 39 ((toys.optflags & FLAG_u) ? gmtime_r : localtime_r)(&now, &tm); 40 41 // Display the date? 42 if (!toys.optargs[0] || toys.optargs[0][0] == '+') { 43 if (toys.optargs[0]) format_string = toys.optargs[0]+1; 44 if (!strftime(toybuf, sizeof(toybuf), format_string, &tm)) 45 perror_msg("bad format `%s'", format_string); 46 47 puts(toybuf); 48 49 // Set the date 50 } else { 51 struct timeval tv; 52 char *s = *toys.optargs; 53 int len = strlen(s); 54 55 if (len < 8 || len > 12 || (len & 1)) error_msg("bad date `%s'", s); 56 57 // Date format: mmddhhmm[[cc]yy] 58 memset(&tm, 0, sizeof(tm)); 59 len = sscanf(s, "%2u%2u%2u%2u", &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, 60 &tm.tm_min); 61 tm.tm_mon--; 62 63 // If year specified, overwrite one we fetched earlier 64 if (len > 8) { 65 sscanf(s, "%u", &tm.tm_year); 66 if (len == 12) tm.tm_year -= 1900; 67 /* 69-99 = 1969-1999, 0 - 68 = 2000-2068 */ 68 else if (tm.tm_year < 69) tm.tm_year += 100; 69 } 70 71 if (toys.optflags & FLAG_u) { 72 // Get the UTC version of a struct tm 73 char *tz = CFG_TOYBOX_FREE ? getenv("TZ") : 0; 74 setenv("TZ", "UTC", 1); 75 tzset(); 76 tv.tv_sec = mktime(&tm); 77 if (CFG_TOYBOX_FREE) { 78 if (tz) setenv("TZ", tz, 1); 79 else unsetenv("TZ"); 80 tzset(); 81 } 82 } else tv.tv_sec = mktime(&tm); 83 84 if (tv.tv_sec == (time_t)-1) error_msg("bad `%s'", toys.optargs[0]); 85 tv.tv_usec = 0; 86 if (!strftime(toybuf, sizeof(toybuf), format_string, &tm)) 87 perror_msg("bad format `%s'", format_string); 88 puts(toybuf); 89 if (settimeofday(&tv, NULL) < 0) perror_msg("cannot set date"); 90 } 91} 92