c++ – How to get the time in seconds of a date in string format?

Question:

I know that the time(0) function returns me the seconds since January 1, 1970, in which case the user would enter a date (dd-mm-yyyy or in any format due to system limitation) and the system would do checking which date is older.

Are there libraries that work with this? What would be the best way to pass a date to the system to transform it in seconds?

Answer:

There is this struct that serves to manipulate dates.

I think what you want is something like this:

#include <stdio.h>
#include <time.h>

int main()
{
    struct tm tm = {};  // inicializa com zeros
    int dia, mes, ano;

    scanf(" %2d-%2d-%4d", &dia, &mes, &ano);
    tm.tm_mday = dia;
    tm.tm_mon  = mes - 1;
    tm.tm_year = ano - 1900;

    time_t tempo = mktime(&tm);
    puts(asctime(&tm));
    printf("%d\n", tempo);
}
Scroll to Top