使用提升日期时间,如何创建用零填充的月份字符串

With Boost datetime how do i create a month string padded with zero?

本文关键字:创建 填充 字符串 日期 时间 何创建      更新时间:2023-10-16

使用提升日期时间,如何在前 9 个月内创建用零填充的月份字符串?

所以我需要"05"而不是"5"。

date Date(2012,05,1);
string monthStringAsNumber = lexical_cast<string>(date.Month().as_number()); 
// returns "5"
string monthStringAsNumberTwo = date.Month().as_short_string();
// returns "Aug"

我想要"05"。我该怎么做?

多谢。

你真的不需要lexical_cast 以下内容应该有效:

stringstream ss;
ss << setw(2) << setfill('0') << date.Month().as_number());
string monthStringAsNumber = ss.str();

或者你可以选择这个嚎叫者:

const string mn[] ={ "01", "02", "03", "04", "05", "06",
                     "07", "08", "09", "10", "11", "12" };
const string& monthStringAsNumber = mn[ date.Month().as_number() ];

一般来说,如果你想以某种自定义格式获取日期时间,你可以检查 http://www.boost.org/doc/libs/1_49_0/doc/html/date_time/date_time_io.html,例如

#include <boost/date_time.hpp>
#include <iostream>
#include <sstream>
#include <string>
int main(int argc, char** argv)
{
    boost::gregorian::date date (2012,5,1);
    boost::gregorian::date_facet* facet = 
            new boost::gregorian::date_facet("%Y %m %d");
    // ^ yes raw pointer here, and don't delete it.
    std::ostringstream ss;
    ss.imbue(std::locale(std::locale(), facet));
    ss << date;
    std::string s = ss.str();
    std::cout << s << std::endl;   // 2012 05 01
    return 0;
}