47

How could I print the current date, using Boost libraries, in the format dd/mm/yyyy H?

What I have:

boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
cout << boost::posix_time::to_simple_string(now).c_str();

2009-Dec-14 23:31:40

But I want:

14-Dec-2009 23:31:40

0

2 Answers 2

81

If you're using Boost.Date_Time, this is done using IO facets.

You need to include boost/date_time/posix_time/posix_time_io.hpp to get the correct facet typedefs (wtime_facet, time_facet, etc.) for boost::posix_time::ptime. Once this is done, the code is pretty simple. You call imbue on the ostream you want to output to, then just output your ptime:

#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>

using namespace boost::posix_time;
using namespace std;

int main(int argc, char **argv) {
  time_facet *facet = new time_facet("%d-%b-%Y %H:%M:%S");
  cout.imbue(locale(cout.getloc(), facet));
  cout << second_clock::local_time() << endl;
}

Output:

14-Dec-2009 16:13:14

See also the list of format flags in the boost docs, in case you want to output something fancier.

5
  • 1
    And boost.org/doc/libs/1_35_0/doc/html/date_time/… for the format flags. Dec 14, 2009 at 23:56
  • 4
    @Jules cout will take ownership. See rhubbarb.wordpress.com/2009/10/17/…
    – RedX
    Feb 21, 2011 at 12:45
  • 3
    The locale takes the ownership. So if you keep this locale stored you can use it any output stream, not just cout
    – CashCow
    Feb 24, 2011 at 17:18
  • 2
    Funny side-node: drove me almost nuts that I could not get it running correctly when trying to get formated date time into std::wstring. I finally realized there is a boost::posix_time::wtime_facet.
    – anhoppe
    Oct 9, 2015 at 10:41
  • 1
    WARNING: don't put time_facet *facet = new time_facet("%d-%b-%Y %H:%M:%S"); in a boost::shared_ptr!!!! you will spend your next day debugging the crazy crash. Apr 12, 2016 at 1:21
1

With the {fmt} library you can print the date in the required format as follows:

#include <boost/date_time/posix_time/posix_time.hpp>
#include <fmt/time.h>

int main() {
  auto now = boost::posix_time::second_clock::local_time();
  fmt::print("{:%d-%b-%Y %H:%M:%S}\n", to_tm(now));
}

This formatting facility is being proposed for standardization in C++20: P0645.

Alternatively you can use std::put_time which was introduced in C++11:

#include <boost/date_time/posix_time/posix_time.hpp>
#include <iomanip>
#include <iostream>

int main() {
  boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
  auto tm = to_tm(now);
  std::cout << std::put_time(&tm, "%d-%b-%Y %H:%M:%S");
}

Disclaimer: I'm the author of {fmt}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.