Boost logo

Boost Users :

Subject: Re: [Boost-users] [date time] How to get "10" and not "Oct"
From: Anthony Foiani (tkil_at_[hidden])
Date: 2011-10-24 14:30:17


"Ken Murphy" <murf_at_[hidden]> writes:

> I have the following code:
>
> std::string db_time()
> {
> typedef boost::posix_time::ptime TimeT;
> TimeT ct = boost::posix_time::microsec_clock::local_time();
> std::stringstream ss;
>
> boost::local_time::local_time_facet* output_facet = new
> boost::local_time::local_time_facet("%Y-%m-%d %h:%m:%s");
> ss.imbue(std::locale(std::locale::classic(), output_facet));
> ss << ct;
>
> return ss.str();
> }
>
> Currently, the following string is returned:
>
> 2011-Oct-24 12:43:05.476990

Really? Even with two duplicate "%m" in the string?

Ah, this is why:

   http://lists.boost.org/boost-users/2006/02/16872.php

Here's what I wrote before I found that:

> How do I get the month as "10" and not as "Oct"?

Traditionally (meaning POSIX 'strftime(3)'), "%M" (note capital "M")
should return the two-digit month:

       %m The month as a decimal number (range 01 to 12).

       %M The minute as a decimal number (range 00 to 59).

You seem to be getting the abbreviated month name, which is "%b":

       %b The abbreviated month name according to the current
              locale.

       %B The full month name according to the current locale.

So the format string that should work for you is:

  %Y-%m-%d %H:%M:%S

(Although I don't know what Boost.DateTime uses for fractional
seconds...)

Finally, recent versions of 'strftime(3)' have started adding
ISO-8601-style output specifiers directly. From a current Linux box:

       %F Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99)

       %G The ISO 8601 week-based year (see NOTES) with century as
              a decimal number. The 4-digit year corresponding to the
              ISO week num$B!>(Bber (see %V). This has the same format
              and value as %Y, except that if the ISO week number
              belongs to the previous or next year, that year is used
              instead. (TZ)

       %T The time in 24-hour notation (%H:%M:%S). (SU)

       %V The ISO 8601 week number (see NOTES) of the current
              year as a decimal number, range 01 to 53, where week 1
              is the first week that has at least 4 days in the new
              year. See also %U and %W. (SU)

According to the Boost.DateTime documentation:

   http://www.boost.org/doc/libs/1_47_0/doc/html/date_time/date_time_io.html#date_time.time_facet

All those format specifiers are supported.

There are also quite a few default formats already built into the
library that are "true" ISO-8601; it might be easier to use those
defaults and then do whatever trivial string manipulation you need to
do to make it fit your requirements.

Best regards,
Tony Foiani


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net