formatting mysql timestamp yyyymmddhhmmss

I am trying to write a timestamp function compatible with a MySQL database TIMESTAMP type. This is what I have so far.
I think it will work except for one problem. I need a fixed precision of
2 digits for months days hours minutes and seconds.
any ideas? I don't think fill() and width() will work for this purpose.
also, if you have any better ideas about how to implement this, I'm all ears.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
string formatTimestamp(){
    time_t rawtime;
    struct tm * utctime;
    time ( &rawtime );
    utctime = gmtime ( &rawtime );
    ostringstream s;
    s << utctime->tm_year + 1900 
      << utctime ->tm_mon + 1 
      << utctime ->tm_mday
      << utctime ->tm_hour
      << utctime ->tm_min
      << utctime ->tm_sec
      << endl;
    string ss=s.str();
    return ss;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <ctime>
#include <string>

std::string now()
{
    std::time_t curr = std::time(nullptr);
    char cstr[128] ;

    // http://en.cppreference.com/w/cpp/chrono/c/strftime
    std::strftime( cstr, sizeof(cstr), "%Y%m%d%H%M%S", std::gmtime(&curr) ) ;

    return cstr ;
}

http://coliru.stacked-crooked.com/a/754971403ffa8044
Topic archived. No new replies allowed.