0

I have this C++ function:

string date()
{
  time_t seconds = time (NULL);

struct tm * timeinfo = localtime (&seconds);

ostringstream oss;
oss << (timeinfo->tm_year + 1900) << "-" << (timeinfo->tm_mon + 1) << "-" << timeinfo->tm_mday; 
string data = oss.str();

return data;
}

The problem is I wanted the month and day with 0's. It's returning '2013-6-1' instead of '2013-06-01'

I'm trying to get this right with some if's and else's but I'm not getting anywhere..

Could you please help me?

João Lima
  • 55
  • 6

2 Answers2

2

You can use the two stream modifiers std::setw and std::setfill with appropriate settings, for instance you can change your code to read:

string date()
{
   time_t seconds = time (NULL);

   struct tm * timeinfo = localtime (&seconds);

   ostringstream oss;
   oss << (timeinfo->tm_year + 1900) << "-" << std::setw(2) << std::setfill('0') << (timeinfo->tm_mon + 1) << "-" << std::setw(2) << std::setfill('0') << timeinfo->tm_mday; 
   string data = oss.str();

   return data;
}
Thomas Russell
  • 5,870
  • 4
  • 33
  • 68
0

You can also use std::put_time, though not implemented in gcc 4.7:

std::string date()
{
    time_t seconds = time (NULL);
    struct tm * timeinfo = localtime (&seconds);
    std::ostringstream oss;
    oss << std::put_time(&timeinfo, "%Y-%m-%d");
    // or: oss << std::put_time(&timeinfo, "%F");
    return oss.str();
}
perreal
  • 94,503
  • 21
  • 155
  • 181