Date and time as string

I want to create a string that holds today's date and another one that hold's the exact time. How can i do this ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include <sstream>
using namespace std;

string months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };


void getDateAndTime( string &date, string &now )
{
   time_t tt = time( 0 );
   tm *t = localtime( &tt );

   // Choose whatever you want from struct tm
   date = to_string( t->tm_mday ) + " " + months[t->tm_mon] + " " + to_string( 1900 + t->tm_year );
   stringstream ss;
   ss.fill( '0' );
   ss << setw( 2 ) << t->tm_hour << ":" << setw( 2 ) << t->tm_min << ":" << setw( 2 ) << t->tm_sec;
   now = ss.str();
}


int main()
{
   string date, now;
   getDateAndTime( date, now );
   cout << date << '\n';
   cout << now  << '\n';
}


You could also look at strftime:
http://www.cplusplus.com/reference/ctime/strftime/
Last edited on
Topic archived. No new replies allowed.