0

The 2nd answer in How do I convert "2012-03-02" into unix epoch time in C? does provides the solution. But it uses tm_yday instead of tm_mday and tm_mon of tm structure.

My Input is human readable date and time and the desired output is UNIX epoch time.

    int main(int argc, char *argv[])
    {
        char timeString[80] = {"05 07 2021 00 33 51"}; //epoch is 1620347631000
        struct tm my_tm = {0};
    
        if(sscanf(timeString, "%d %d %d %d %d %d",  &my_tm.tm_mon, &my_tm.tm_mday, &my_tm.tm_year, &my_tm.tm_hour, &my_tm.tm_min, &my_tm.tm_sec)!=6)
        {
            /* ... error parsing ... */
            printf(" sscanf failed");
        }
    
        // In the below formula, I can't use my_tm.tm_yday as I don't have the value for it. 
        //I want to use my_tm.tm_mday and tm_mon. 
        printf("%d",my_tm.tm_sec + my_tm.tm_min*60 + my_tm.tm_hour*3600 + my_tm.tm_yday*86400 +
            (my_tm.tm_year-70)*31536000 + ((my_tm.tm_year-69)/4)*86400 -
            ((my_tm.tm_year-1)/100)*86400 + ((my_tm.tm_year+299)/400)*86400 );
    
        return EXIT_SUCCESS;
    }

So, in other words, I'm looking for a replacement for my_tm.tm_yday*86400 in terms of my_tm.tm_mday and my_tm.tm_mon

Gow.
  • 55
  • 9
  • Please describe the problem. What is the input data you're working with? What is the desired output or state? Where is your code? – Cheatah May 14 '21 at 10:50
  • https://github.com/bminor/newlib/blob/7b8edba6259fd8439fada6a2aaf1ecdef7b509d8/newlib/libc/time/mktime.c#L165 – Hans Passant May 14 '21 at 11:34
  • Use `mktime` as in [this answer](https://stackoverflow.com/a/9542298/5264491) of the question you linked to. Note that you should set `tm.tm_year` to the actual year minus 1900, and set `tm.tm_mon` to the actual month minus 1. – Ian Abbott May 14 '21 at 12:28

1 Answers1

0

A year in the range "date of adoption of Gregorian calendar" to INT_MAX and a month in the range 1 to 12 can be converted to a zero-based "year day" in the range 0 to 365 by the following helper function:

int yday(int year, int month)
{
    static const short int upto[12] =
        {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
    int yd;

    yd = upto[month - 1];
    if (month > 2 && isleap(year))
        yd++;
    return yd;
}

That uses the following helper function isyear that takes a year in the range "date of adoption of Gregorian calendar" to INT_MAX and returns 0 if the year is not a leap year, 1 if the year is a leap year:

int isleap(int year)
{
    return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
Ian Abbott
  • 15,083
  • 19
  • 33