使用提升日期时间,如何创建用零填充的月份字符串
With Boost datetime how do i create a month string padded with zero?
使用提升日期时间,如何在前 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;
}
相关文章:
- C++ 双向链表:使用矩阵类成员创建和填充列表
- CGAL:如何创建填充边界曲线的曲面网格?
- 创建整数的 2D 数组,该数组将使用两个函数用随机数填充矩阵.我做错了什么?
- 如何创建一个新的二进制文件并用常量值填充它?
- 如何创建和填充 jsoncpp 数组 (jsoncpp.sourceforge)
- 在循环中创建和填充向量
- C++填充一个std::map创建不必要的对象
- 提升:创建对象并用线程填充矢量
- 如何创建 std::vector of char/std::byte,其中第一个字节对齐到 16 个字节,但没有填充
- 矢量填充比创建新矢量慢
- 如何就地创建 + 填充容器
- 是一个哨兵 QWidget 一个好主意(以防止在创建和填充布局时出现内存泄漏)
- 如何创建一个ifstream对象的数组,以及如何使用编号的文本文件填充该数组
- C++动态创建的MFC视觉工作室填充组合框
- 当您有结构名称和字段值的列表时,是否可以以编程方式创建结构的对象并填充字段
- WTableView中的QueryModel:请举例说明如何添加一行并用刚刚创建的新记录填充它
- MFC PreCreateWindow,用于创建一个填充除任务栏之外的屏幕的窗口
- 使用提升日期时间,如何创建用零填充的月份字符串
- Ncurses:在列之间创建填充空间
- GDI+正在创建填充的CustomLineCap