5

With Howard Hinnant's date.h (I am using C++17), how can I get Monday's date and Friday's date using the library?

I can get today's date using this:

auto todayDate = date::floor<date::days>(std::chrono::system_clock::now());

std::cout << date::format("%F", todayDate) << "\n";

But I would like to get the dates for the work week (Monday - Friday)

1 Answer 1

7

To get the dates of Monday and Friday, you can do it like so by adapting the logic given by Howard Hinnant's answer here:

auto todayDate = date::floor<date::days>(std::chrono::system_clock::now());
std::cout << date::format("%F", todayDate) << "\n";

auto mondayDate = todayDate - (date::weekday{ todayDate } - date::Monday);
std::cout << date::format("%F", mondayDate) << "\n";

auto fridayDate = mondayDate + (mondayDate - date::Thursday);
std::cout << date::format("%F", fridayDate) << "\n";

If you need the Unix timestamp version:

auto mondayTimestamp = mondayDate.time_since_epoch();
auto mondayDateSeconds = std::chrono::duration_cast<std::chrono::seconds>(mondayTimestamp).count();

auto fridayTimestamp = fridayDate.time_since_epoch();
auto fridaySeconds = std::chrono::duration_cast<std::chrono::seconds>(fridayTimestamp).count();

This should also work for the new C++20 <chrono> library as essentially it's Howard's library underneath

Sign up to request clarification or add additional context in comments.

2 Comments

auto fridayDate = mondayDate + (mondayDate - date::Thursday); looks wrong to me. Shouldn't that be auto fridayDate = mondayDate + (date::Friday - mondayDate); instead? Or simpler, you know how many days are between Monday and Friday, and we're not likely to add new weekdays to the calendar anytime soon, so just hard-code it: auto fridayDate = mondayDate + 4;
These are good points and something a viewer of this question can use. I got my approach while I was still new to the library and that code worked for me. I haven't tested your code, but it will no doubt work the same :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.