Re: [Cppcms-users] C++ locale and boost.locale
Brought to you by:
artyom-beilis
|
From: Artyom <art...@ya...> - 2011-05-04 16:52:53
|
>
> BTW, thanks to your help, I got the missing piece, so that I finally managed
>to
>
> do what I wanted to do:
>
> #include <sstream>
> #include <boost/locale.hpp>
>
> std::string timestamp_to_string(time_t const& tt) {
> using namespace boost::locale;
> generator gen;
> std::locale::global(gen("en_US.UTF-8"));
> std::stringstream ss;
> ss.imbue(std::locale());
> ss << as::date << tt << " ";
> ss << as::time << tt << std::endl;
> std::string r = "";
> getline(ss, r);
> return r;
> }
>
Few points:
> timestamp_to_string(time_t const& tt)
It is better to write
timestamp_to_string(time_t tt)
As time_t is integral type and it is better
to pass it by value.
> using namespace boost::locale;
> generator gen;
> std::locale::global(gen("en_US.UTF-8"));
> ss.imbue(std::locale());
Is very inefficient as locale generation is very
heavy procedure.
In CppCMS context you have this member function:
http://cppcms.sourceforge.net/cppcms_ref_v0_99/classcppcms_1_1http_1_1context.html#39fde738210daf84deee691f45260e5b
So basically inside cppcms::application based class just write
std::locale loc = context().locale();
or
std::locale loc = context().locale("en_US.UTF-8");
It returns the locale defined in configuration file for you
and it would cache the locale automatically for future use.
> std::locale::global(gen("en_US.UTF-8"));
> ss.imbue(std::locale());
Even if you use it, it is better to write
ss.imbue(gen("en_US.UTF-8"));
And not set global locale and then create a locale
instance from global one.
> ss << as::date << tt << " ";
> ss << as::time << tt << std::endl;
It is better to write
ss << as::datetime << tt;
> std::string r = "";
r is empty by default, no need r="";
> getline(ss, r);
> return r;
It is better to call
return ss.str()
Of course without "<<std::endl"
> It took me 10-20 hours to research, read and understand enough to come up with
>
> the seemingly simple piece of code above. :-/
>
> I use it to format unix timestamps before pushing it to my
> cppcms::base_content object.
>
> I don't know if it's the right approach, but it works...
>
It is much simpler, you have filers namespace
http://cppcms.sourceforge.net/cppcms_ref_v0_99/namespacecppcms_1_1filters.html
So just write in the template
<% tt | datetime %>
Or even with more fine grained control
<% tt | strftime("%Y-%m-%d %H:%M:%S %Z") %>
where tt is just time_t in your context :-)
>
>
> Augustin.
Best,
Artyom
|