How to convert date string to tm_wday in tm structure

I have a date string format, for example "2010-03-01", and I want to get the equivalent of "tm_wday", for example, Monday, Tuesday ...

Can someone give me a hint on how to achieve this in c?

+4
source share
2 answers

Check the strptime() function:

 char *strptime(const char *s, const char *format, struct tm *tm); 

The strptime () function is the inverse of the strftime (3) function and converts the character string pointed to by s, the values ​​that are stored in the tm structure pointed to by tm, using the format specified in the format.

+3
source

Use mktime() to calculate the day of the week.

 #include <memory.h> #include <stdio.h> #include <time.h> int main(void) { const char *p = "2010-03-01"; struct tm t; memset(&t, 0, sizeof t); // set all fields to 0 if (3 != sscanf(p,"%d-%d-%d", &t.tm_year, &t.tm_mon, &t.tm_mday)) { ; // handle error; } // Adjust to struct tm references t.tm_year -= 1900; t.tm_mon--; // Calling mktime will set the value of tm_wday if (mktime(&t) < 0) { ; // handle error; } printf("DOW(%s):%d (0=Sunday, 1=Monday, ...)\n", p, t.tm_wday); // DOW(2010-03-01):1 (0=Sunday, 1=Monday, ...) return 0; } 
+1
source

All Articles