Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format date time object with format dd/mm/yyyy?

Tags:

c++

date

boost

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

like image 923
Alfredo Avatar asked Dec 14 '09 23:12

Alfredo


People also ask

How do you format a Date mm dd yyyy?

From mm/dd/yyyy to dd/mm/yyyy To change the date display in Excel follow these steps: Go to Format Cells > Custom Enter dd /mm /yyyy in the available space.

How do I convert DateTime to Date format?

To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.

How can change Date format in dd mm yyyy in HTML?

To set and get the input type date in dd-mm-yyyy format we will use <input> type attribute. The <input> type attribute is used to define a date picker or control field. In this attribute, you can set the range from which day-month-year to which day-month-year date can be selected from.


1 Answers

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.

like image 83
Todd Gamblin Avatar answered Oct 19 '22 01:10

Todd Gamblin