João Lima
João Lima

Reputation: 55

C++ function to return current date (with zeros in month and day)

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?

Upvotes: 0

Views: 2593

Answers (2)

perreal
perreal

Reputation: 97948

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();
}

Upvotes: 0

Thomas Russell
Thomas Russell

Reputation: 5980

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;
}

Upvotes: 2

Related Questions