如何将boost :: gregorian :: date转换为mm/dd/yyyy格式,反之亦然? [英] How to convert boost::gregorian::date to mm/dd/yyyy format and vice versa?

查看:218
本文介绍了如何将boost :: gregorian :: date转换为mm/dd/yyyy格式,反之亦然?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Boost具有转换为以下描述的其他字符串格式的几种功能 ),但没有转换为必要的mm/dd/yyyy格式.目前,我正在通过以下方式进行操作:

Boost has several functions converting to other string formats described here, but there is no conversion into the necessary mm/dd/yyyy format. Currently I am doing it the following way:

 std::string dateAsMMDDYYYY( const boost::gregorian::date& date )
 {
    std::string yyyymmdd = boost::gregorian::to_iso_string( date );
    std::string ret = yyyymmdd.substr(4,2) + "/" + yyyymmdd.substr(6,2) + "/" + yyyymmdd.substr(0,4);
    return ret;
 }

即只是将数字从to_iso_string()返回的值中删除即可.这似乎很不礼貌,我正在寻找一种更优雅的方式来执行此转换.我还需要有关如何执行向后转换的建议(即从'mm/dd/yyyy'字符串转换为boost :: gregorian :: date)

i.e. just cutting the numbers out of the value returned by to_iso_string(). This seems very rude, and I am looking for a more elegant way to perform this conversion. Also I need an advice about how to perform a backward conversion (i.e. from 'mm/dd/yyyy' string to boost::gregorian::date)

感谢您的帮助.预先感谢.

Any help is appreciated. Thanks in advance.

推荐答案

boost具有相当多用途的

boost has fairly versatile date/time IO facilities

const std::locale fmt(std::locale::classic(),
                      new boost::gregorian::date_facet("%m/%d/%Y"));
std::string dateAsMMDDYYYY( const boost::gregorian::date& date )
{
    std::ostringstream os;
    os.imbue(fmt);
    os << date;
    return os.str();
}

逆转换:

const std::locale fmt2(std::locale::classic(),
                       new boost::gregorian::date_input_facet("%m/%d/%Y"));
boost::gregorian::date MMDDYYYYasDate( const std::string& str)
{
    std::istringstream is(str);
    is.imbue(fmt2);
    boost::gregorian::date date;
    is >> date;
    return date;
}

这篇关于如何将boost :: gregorian :: date转换为mm/dd/yyyy格式,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆