With as little blood as possible, can there be already prepared libraries? Moreover, note: the date may be up to 1970. Generally it is the date of birth. Who will advise what?

    2 answers 2

    I advise you to abandon the type time_t. And although it is possible to save dates before 1970 (in the form of negative numbers), it is better to never do this. The type is made symbolic not to store negative numbers in it. It is necessary for another. Functions that work with time, it is convenient to do so that in case of success they return time, and in case of failure - a negative error code.

    • If I could refuse, I would have done it a long time ago. - VorobyevEvgeniy

    There is such a library. Standard libc.

    #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // yyyymmddhhmmss main (int ac, char *av[]) { struct tm t; const char *p = "yyyymmddhhmmss"; if (av[1]) { char buf[1024]; if (sscanf(av[1],"%s",buf) != 1) { Err:; printf ("Invalid argument [%s]\n",av[1]); exit (1); } if (strlen(buf) != strlen(p)) goto Err; strncpy(buf,av[1],4); buf[4] = 0; if ((t.tm_year = atoi(buf)) < 1) goto Err; t.tm_year -= 1900; strncpy(buf,av[1]+4,2); buf[2] = 0; if ((t.tm_mon = atoi(buf)) < 1 || t.tm_mon > 12) goto Err; t.tm_mon--; strncpy(buf,av[1]+6,2); buf[2] = 0; if ((t.tm_mday = atoi(buf)) < 1 || t.tm_mday > 31) goto Err; strncpy(buf,av[1]+8,2); buf[2] = 0; if ((t.tm_hour = atoi(buf)) < 0 || t.tm_hour > 23) goto Err; strncpy(buf,av[1]+10,2); buf[2] = 0; if ((t.tm_min = atoi(buf)) < 0 || t.tm_min > 59) goto Err; strncpy(buf,av[1]+12,2); buf[2] = 0; if ((t.tm_sec = atoi(buf)) < 0 || t.tm_sec > 59) goto Err; p = "Your"; } else { t.tm_sec = 10; t.tm_min = 20; t.tm_hour = 11; t.tm_mday = 21; t.tm_mon = 0; t.tm_year = 59; p = "My"; } time_t tt = mktime(&t); if ((long)tt == -1) goto Err; printf ("%s birthday: %s\n",p,ctime(&tt)); exit (fflush(stdout) == EOF); } 

    Parsing the string yyyymmdd ... do as you like, and the rest of IMHO is understandable.

    • True, it should be noted that on a 32-bit machine, this code works for dates in the range from about 1902 to 2038. - avp pm
    • @avp And, for example, here's the situation [ in this ] [1]. Parsing the time and dates, as far as I know, is a very difficult and non-trivial task. [1]: habrahabr.ru/post/145857 - Costantino Rupert
    • Yes, and yet it is not quite right for February, it takes dates. You can set, for example, 31 and the response will be 3 March. Just showed TS mktime (). - As for doing yourself or search. IMHO always try yourself first, if the initial version is not communicated, then understand. Otherwise there will be no success. - avp