1

我试图在我的代码中处理日期和时间,并且已经指向了 boost 库的方向——特别是 boost::locale::date_time (部分是因为这让我避免了夏令时的怪异,这让我以前的实施困难)。

但是,我得到的结果不一致。当我将日期存储在 date_time 对象中,然后尝试从中获取数据时,这是不正确的。这是一个例子:

#include <boost\\asio\\error.hpp>
#include <boost\\locale.hpp>
using namespace std;

int main()
{
    // Necessary to avoid bad_cast exception - system default should be fine
    boost::locale::generator gen;
    std::locale::global(gen(""));

    // Create date_time of 12/19/2016
    boost::locale::date_time dt = boost::locale::period::year(2016) + boost::locale::period::month(12) + boost::locale::period::day(19);

    unsigned int month = dt.get(boost::locale::period::month());
    unsigned int day = dt.get(boost::locale::period::day());
    unsigned int year = dt.get(boost::locale::period::year());

    cout << month << "/" << day << "/" << year << endl;

    // Expected output:  12/19/2016
    // Actual output:    0/19/2017
}

我究竟做错了什么?我只想提取保存的天、月、年、小时等。

谢谢你。

编辑:我最初可能以不正确的方式设置 date_time 。假设我有整数(不是字符串)格式的所有相关数据,是否有更好的方法来显式设置日期时间(例如,设置为 2016 年 12 月 19 日)?

4

1 回答 1

1

2016-04-05+ 12 months= 2017-04-05。这是有道理的,因为 12 个月是一整年。

尝试添加 11 个月,然后递增以从基于 0 的月份调整为基于 1 的月份。

boost::locale::date_time dt = boost::locale::period::year(2016) + boost::locale::period::month(11) + boost::locale::period::day(19);

uint month = dt.get(boost::locale::period::month()) + 1;
uint day = dt.get(boost::locale::period::day());
uint year = dt.get(boost::locale::period::year());

cout << month << "/" << day << "/" << year << endl;
于 2017-06-28T20:21:08.560 回答