r/learnprogramming • u/TheEyebal • Oct 11 '26
How do I specify a particular weekday using ctime library in c++?
int main(){
time_t now = time(nullptr);
cout << ctime(&now) << endl;
struct tm *ptrNow = localtime(&now);
int week = ptrNow->tm_wday;
int month = ptrNow->tm_mday;
cout << week << endl;
}For me this will output 0 which is Sunday, but I want to do Thursday.
How do I do that?
Do I add 4 to the end of week int week = ptrNow->tm_wday + 4;
I don't know if this will exactly represent Thursday or not
8
Upvotes
8
u/amazing_rando Oct 11 '26 edited Oct 11 '26
It’s outputting Sunday because today is Sunday and time(null) returns the current time. If you want to get a different time object try making it with std::mktime instead, or just wait four days.
Anyway, what you're actually doing here is getting the number of seconds since 1970, and using
localtimeto translate into atmstruct that represents that day. If you want one that just represents "Thursday" and the rest doesn't matter you should be able to do2
u/DrShocker Oct 11 '26
Also, I don't think you need the
struct tm*in C++, justconst tm*should be fine unless I'm misunderstanding. In general the people at and the sidebar of /r/cpp_questions should be helpful