8

Forgive the simple question, but I've been at this for hours, with no success. Im trying to implement a function:

std::string make_date_string()

I am using Howard Hinnant's date lib, which allows me to do stuff like this:

cout << floor<days>(system_clock::now());

printing something like:

2017-07-09

I'm trying to figure out how I can get that output to go in a std::string so I can return it from my function, but Im getting nowhere.

2 Answers 2

10

I'm trying to figure out how I can get that output to go in a std::string so I can return it from my function, but Im getting nowhere.

In such case you can use a std::ostringstream:

std::ostringstream oss;
oss << floor<days>(system_clock::now());
std::string time = oss.str();

As a side note:

As it looks like your helper function

template<typename Fmt>
floor(std::chrono::timepoint);

is implemented as an iostream manipulator, it can be used with any std::ostream implementation.

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

1 Comment

I was finally able to complete my quest of creating a date/time string without using ctime in a portable way, what an age we live in!
3

The accepted answer is a good answer (which I've upvoted).

Here is an alternative formulation using the same library:

#include "date.h"
#include <string>

std::string
make_date_string()
{
    return date::format("%F", std::chrono::system_clock::now());
}

which creates a std::string with the "2017-07-09" format. This particular formulation is nice in that you don't have to explicitly construct a std::ostringstream, and you can easily vary the format to whatever you like, for example:

    return date::format("%m/%d/%Y", std::chrono::system_clock::now());

which now returns "07/09/2017".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.