简体   繁体   English

C ++函数返回当前日期(月和日零)

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

I have this C++ function: 我有这个C ++函数:

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. 问题是我想要0和0的月和日。 It's returning '2013-6-1' instead of '2013-06-01' 它正在回归'2013-6-1'而不是'2013-06-01'

I'm trying to get this right with some if's and else's but I'm not getting anywhere.. 我试图用一些if和其他的方式做到这一点,但我没有得到任何地方..

Could you please help me? 请你帮助我好吗?

You can use the two stream modifiers std::setw and std::setfill with appropriate settings, for instance you can change your code to read: 您可以使用两个流修饰符std::setwstd::setfill进行适当的设置,例如,您可以将代码更改为:

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

You can also use std::put_time , though not implemented in gcc 4.7: 你也可以使用std :: put_time ,虽然没有在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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM