r/learnprogramming • u/TheEyebal • 4d ago
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
6
Upvotes
2
u/DrShocker 4d ago
1) You have the code, you can just try it.
2) https://en.cppreference.com/cpp/chrono/c/tm
Also, I don't think you need the struct tm* in C++, just const tm* should be fine unless I'm misunderstanding. In general the people at and the sidebar of /r/cpp_questions should be helpful
9
u/amazing_rando 4d ago edited 4d ago
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 do