Showing results for 
Search instead for 
Did you mean: 

Converting ASCII date & Time to time_t (long) variable


Converting ASCII date & Time to time_t (long) variable

I need to convert a string containing ASCII time and date (such as "Sun Sep 17 15:12:07 2006") to a time_t variable (or long). Converting time_t to ASCII is no problem (asctime). The other way around is a problem. Can anybody help me?
0 Kudos
Message 1 of 2

Re: Converting ASCII date & Time to time_t (long) variable

Basically the answer is: scan the string for separate components of date and time and fill the corresponding fields of a tm struct with the correct casting or adaptations (for example month is in the range 0÷11), next use mktime () function to obtain the corresponding time_t value. When using mktime () function, tm_yday and tm_wday are ignored.

Look at this example taken from Harbison & Steele manual:


#include <time.h>


double Secs_Since_April_15 () {
    struct tm Apr_15_struct = { 0 };
    time_t    Apr_15_t;

    Apr_15_struct.tm_year = 90;
    Apr_15_struct.tm_mon = 3;
    Apr_15_struct.tm_mday = 15;
    Apr_15_t = mktime (&Apr_15_struct);
    if (Apr_15_t == (yime_t)-1)     // Error
        return 0.0;
        return difftime (time (NULL), Apr_15_t);

Proud to use LW/CVI from 3.1 on.

My contributions to the Developer Community
If I have helped you, why not giving me a kudos?
0 Kudos
Message 2 of 2