getting day of week
-
Hi! how do i convert a date to struct tm? i want to get day of week for this date. this code has a run time error:
// date : 2010/07/12
int yy = 2010;
int mm = 07;
int dd = 12;
struct tm tt;
time_t t;
yy -= 1900;
tt.tm_mon = mm;
tt.tm_year = yy;
tt.tm_mday = dd;
t = mktime(&tt);
struct tm *tt2 = localtime(&t);
int ii = tt2->tm_wday; // run time error ?!!!!please help me.
Zo.Naderi-Iran
-
Hi! how do i convert a date to struct tm? i want to get day of week for this date. this code has a run time error:
// date : 2010/07/12
int yy = 2010;
int mm = 07;
int dd = 12;
struct tm tt;
time_t t;
yy -= 1900;
tt.tm_mon = mm;
tt.tm_year = yy;
tt.tm_mday = dd;
t = mktime(&tt);
struct tm *tt2 = localtime(&t);
int ii = tt2->tm_wday; // run time error ?!!!!please help me.
Zo.Naderi-Iran
zon_cpp wrote:
time_t t;
time_t t = {0};
i.e. never, never, never forget variable initialization. :)
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
[My articles] -
Hi! how do i convert a date to struct tm? i want to get day of week for this date. this code has a run time error:
// date : 2010/07/12
int yy = 2010;
int mm = 07;
int dd = 12;
struct tm tt;
time_t t;
yy -= 1900;
tt.tm_mon = mm;
tt.tm_year = yy;
tt.tm_mday = dd;
t = mktime(&tt);
struct tm *tt2 = localtime(&t);
int ii = tt2->tm_wday; // run time error ?!!!!please help me.
Zo.Naderi-Iran
I can't see what's wrong with your code (but there could be something in there, it's a bit convoluted) but this works on my compiler and uses the same function calls:
std::tm t = { 0, 0, 12, 13, 6, 110 }; std::time\_t int\_rep( std::mktime( &t ) ); t = \*std::localtime( &int\_rep ); std::cout << std::asctime( &t ) << std::endl;
It's a bit disgusting but seems to get the job done. I'd be tempted to wrap it up in a function though:
int day_of_week( int day, int month, int year )
{
std::tm t = { 0, 0, 12, day, month - 1, year - 1900 };
std::time_t gratuitous_l_value( std::mktime( &t ) );
return std::localtime( &gratuitous_l_value )->tm_wday;
}If you're programming in C and not C++ just remove the std:: everywhere, include time.h and not ctime and convert the constructor style initialisations to = and it'll probably work. Cheers, Ash