Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Formatted Date

Tags:

c++

date

boost

This might be a VERY simple question, but coming from the PHP world, is there a SIMPLE (not around-the-world) way to output the current date in a specific format in C++?

I'm looking to express the current date as "Y-m-d H:i" (PHP "date" syntax), comes out like "2013-07-17 18:32". It'd always be expressed with 16 characters (incl. leading zeros).

I am fine including Boost libraries if that helps. This is vanilla/linux C++ though (no Microsoft headers).

Thanks so much!

like image 320
Harry Avatar asked Dec 26 '22 01:12

Harry


2 Answers

strftime is the simplest I can think of without boost. Ref and exemple: http://en.cppreference.com/w/cpp/chrono/c/strftime

like image 103
rectummelancolique Avatar answered Dec 29 '22 03:12

rectummelancolique


You mean something like this:

#include <iostream>
#include <ctime>

using namespace std;

int main( )
{
   // current date/time based on current system
   time_t now = time(0);

   // convert now to string form
   char* dt = ctime(&now);

   cout << "The local date and time is: " << dt << endl;

   // convert now to tm struct for UTC
   tm *gmtm = gmtime(&now);
   dt = asctime(gmtm);
   cout << "The UTC date and time is:"<< dt << endl;
}

result:

The local date and time is: Sat Jan  8 20:07:41 2011

The UTC date and time is:Sun Jan  9 03:07:41 2011
like image 37
Varvarigos Emmanouil Avatar answered Dec 29 '22 04:12

Varvarigos Emmanouil