简体   繁体   English

boost :: locale :: date_time:如何在Boost C ++中从date_time对象获取数据?

[英]boost::locale::date_time: How to get data from date_time object in Boost C++?

I'm trying to handle dates and times in my code, and have been pointed in the direction of the boost library - specifically, boost::locale::date_time (in part because this lets me avoid Daylight Saving Time weirdness that was making my previous implementation difficult). 我正在尝试处理代码中的日期和时间,并且已将其指向boost库的方向-特别是boost :: locale :: date_time(部分原因是因为这避免了使我的夏令时怪异现象以前的实现困难)。

However, I'm getting inconsistent results. 但是,我得到的结果不一致。 When I store a date in the date_time object and later try to get data from it, it is incorrect. 当我将日期存储在date_time对象中并稍后尝试从中获取数据时,它是不正确的。 Here's an example: 这是一个例子:

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

What am I doing wrong? 我究竟做错了什么? I just want to extract the saved days, months, years, hours, etc. 我只想提取保存的天,月,年,小时等。

Thank you. 谢谢。

EDIT: It's possible I'm initially setting the date_time in an incorrect manner. 编辑:很可能我最初以错误的方式设置了date_time。 Is there a better way to explicitly set a date time (for instance, to 12-19-2016), assuming I have all the relevant data in integer (not string) format? 假设我所有相关数据都为整数(不是字符串)格式,是否有更好的方法来显式设置日期时间(例如,设置为2016年12月19日)?

2016-04-05 + 12 months = 2017-04-05 . 2016-04-05 + 12 months = 2017-04-05 This makes sense, since 12 months is a whole year. 这很有意义,因为12个月是一年。

Try adding 11 months instead, then increment to adjust from a 0-based month to a 1-based month. 尝试添加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;

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

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