logo

utils

~/.local/bin tools and git-hooks

date.c (1095B)


      1 /* Copyright CC-BY-SA-4.0 2017-2018 Haelwenn (lanodan) Monnier <contact@hacktivis.me> */
      2 #include <locale.h> /* setlocale() */
      3 #include <stdio.h>  /* BUFSIZ, perror(), puts() */
      4 #include <stdlib.h> /* exit() */
      5 #include <time.h>   /* time, localtime, tm, strftime */
      6 #include <unistd.h> /* getopt(), optarg, optind */
      7 
      8 int main(int argc, char *argv[])
      9 {
     10 	char outstr[BUFSIZ];
     11 	struct tm *tm;
     12 	time_t now;
     13 	char *format  = "%c";
     14 	int uflag = 0, dflag = 0;
     15 	int c;
     16 
     17 	setlocale(LC_ALL, "");
     18 
     19 	while ((c = getopt(argc, argv, ":ud:")) != -1) {
     20 		switch(c) {
     21 		case 'd': /* user-provided datetime */
     22 			now = time(optarg);
     23 			dflag++;
     24 			break;
     25 		case 'u': /* Timezone is UTC */
     26 			uflag++;
     27 			break;
     28 		}
     29 	}
     30 
     31 	if(!dflag)
     32 		now = time(NULL);
     33 
     34 	if(uflag)
     35 		tm = gmtime(&now);
     36 	else
     37 		tm = localtime(&now);
     38 
     39 	argc -= optind;
     40 	argv += optind;
     41 
     42 	if (*argv && **argv == '+')
     43 		format = *argv + 1;
     44 
     45 	if(tm == NULL)
     46 	{
     47 		perror("localtime");
     48 		exit(EXIT_FAILURE);
     49 	}
     50 
     51 	if(strftime(outstr, sizeof(outstr), format, tm) == 0)
     52 	{
     53 		perror("strftime returned 0");
     54 		exit(EXIT_FAILURE);
     55 	}
     56 
     57 	return puts(outstr);
     58 }