Search code examples
c++c++14durationc++-chrono

Convert Milliseconds to Duration with the given format


For a given duration of 203443 milliseconds (this is 3 minutes, 23 seconds and 443 milliseconds), a pattern like e.g.

This took about' m 'minutes and' s 'seconds.

would produce the following formatted output:

This took about 3 minutes and 23 seconds.

It is different from format timestamp to current date-time. Is there any C++ standard Library (under C++14) or a solution that I can follow. I'm new to C++.


Solution

  • #include <chrono>
    #include <iostream>
    
    int
    main()
    {
        using namespace std::chrono;
        auto d = 203443ms;
        auto m = duration_cast<minutes>(d);
        d -= m;
        auto s = duration_cast<seconds>(d);
        std::cout << "This took about " << m.count() << " minutes and "
                                        << s.count() << " seconds.\n";
    }