Implementations of common Unix command-line utilities written in C.
unix-tools / date.c
| 1 | #define _POSIX_C_SOURCE 200809L |
| 2 | #include <unistd.h> |
| 3 | #include <errno.h> |
| 4 | #include <inttypes.h> |
| 5 | #include <stdio.h> |
| 6 | #include <stdlib.h> |
| 7 | #include <string.h> |
| 8 | #include <time.h> |
| 9 | |
| 10 | int |
| 11 | main(int argc, char **argv) |
| 12 | { |
| 13 | int option, uflg = 0, nflg = 0, iflg = 0, tflg = 0; |
| 14 | time_t now; |
| 15 | struct tm *tm; |
| 16 | char buf[128]; |
| 17 | while ((option = getopt(argc, argv, "unit")) != -1) { |
| 18 | if (option == 'u') uflg = 1; |
| 19 | else if (option == 'n') nflg = 1; |
| 20 | else if (option == 'i') iflg = 1; |
| 21 | else if (option == 't') tflg = iflg = 1; |
| 22 | else goto usage; |
| 23 | } |
| 24 | if (argc - optind > 1) goto usage; |
| 25 | if (optind < argc) { |
| 26 | char *end; |
| 27 | intmax_t seconds; |
| 28 | errno = 0; |
| 29 | seconds = strtoimax(argv[optind], &end, 0); |
| 30 | if (errno || !*argv[optind] || *end || (intmax_t)(time_t)seconds != seconds) goto usage; |
| 31 | now = (time_t)seconds; |
| 32 | } else { |
| 33 | now = time(NULL); |
| 34 | if (now == (time_t)-1) { perror("date: time"); return 1; } |
| 35 | } |
| 36 | if (nflg) printf("%jd\n", (intmax_t)now); |
| 37 | else { |
| 38 | tm = uflg ? gmtime(&now) : localtime(&now); |
| 39 | if (tm == NULL) { perror("date: time conversion"); return 1; } |
| 40 | if (!strftime(buf, sizeof(buf), iflg ? |
| 41 | (tflg ? "%Y-%m-%dT%H:%M:%S%z" : "%Y-%m-%d") : |
| 42 | "%a %b %e %H:%M:%S %Y", tm)) { |
| 43 | fprintf(stderr, "date: formatting failed\n"); return 1; |
| 44 | } |
| 45 | if (tflg) { |
| 46 | size_t n = strlen(buf); |
| 47 | if (n >= 5 && strcmp(buf + n - 5, "+0000") == 0) strcpy(buf + n - 5, "Z"); |
| 48 | } |
| 49 | puts(buf); |
| 50 | } |
| 51 | if (fflush(stdout) == EOF || ferror(stdout)) { perror("date: stdout"); return 1; } |
| 52 | return 0; |
| 53 | usage: |
| 54 | fprintf(stderr, "usage: %s [-unit] [seconds]\n", argv[0]); |
| 55 | return 1; |
| 56 | } |