date.c (1946B)
- // Collection of Unix tools, comparable to coreutils
- // SPDX-FileCopyrightText: 2017-2022 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
- // SPDX-License-Identifier: MPL-2.0
- #define _POSIX_C_SOURCE 200809L
- #include "../lib/iso_parse.h" /* iso_parse */
- #include <errno.h> /* errno */
- #include <locale.h> /* setlocale() */
- #include <stdio.h> /* BUFSIZ, perror(), puts() */
- #include <stdlib.h> /* exit(), strtol() */
- #include <time.h> /* time, localtime, tm, strftime */
- #include <unistd.h> /* getopt(), optarg, optind */
- void
- usage()
- {
- fprintf(stderr, "date [-uR][-d datetime] [+format]\n");
- }
- int
- main(int argc, char *argv[])
- {
- char outstr[BUFSIZ];
- struct tm *tm;
- time_t now;
- char *format = "%c";
- int uflag = 0;
- int c;
- setlocale(LC_ALL, "");
- now = time(NULL);
- if(now == (time_t)-1)
- {
- perror("date: time");
- exit(EXIT_FAILURE);
- }
- while((c = getopt(argc, argv, ":d:uR")) != -1)
- {
- switch(c)
- {
- case 'd': /* Custom datetime */
- now = iso_parse(optarg).tv_sec;
- break;
- case 'u': /* UTC timezone */
- uflag++;
- break;
- case 'R': /* Email (RFC 5322) format */
- format = "%a, %d %b %Y %H:%M:%S %z";
- break;
- case ':':
- fprintf(stderr, "date: Error: Missing operand for option: '-%c'\n", optopt);
- usage();
- return 1;
- case '?':
- fprintf(stderr, "date: Error: Unrecognised option: '-%c'\n", optopt);
- usage();
- return 1;
- }
- }
- if(uflag)
- {
- tm = gmtime(&now);
- if(tm == NULL)
- {
- perror("date: gmtime");
- exit(EXIT_FAILURE);
- }
- }
- else
- {
- tm = localtime(&now);
- if(tm == NULL)
- {
- perror("date: localtime");
- exit(EXIT_FAILURE);
- }
- }
- argc -= optind;
- argv += optind;
- (void)argc;
- if(*argv && **argv == '+') format = *argv + 1;
- errno = 0;
- if(strftime(outstr, sizeof(outstr), format, tm) == 0 && errno != 0)
- {
- perror("date: strftime");
- exit(EXIT_FAILURE);
- }
- if(puts(outstr) < 0)
- {
- perror("date: puts");
- exit(EXIT_FAILURE);
- }
- return 0;
- }