Namespaces
Variants

std::time_get<CharT,InputIt>:: get_date, std::time_get<CharT,InputIt>:: do_get_date

From cppreference.net
定义于头文件 <locale>
public :

iter_type get_date ( iter_type beg, iter_type end, std:: ios_base & str,

std:: ios_base :: iostate & err, std:: tm * t ) const ;
(1)
protected :

virtual iter_type do_get_date ( iter_type beg, iter_type end, std:: ios_base & str,

std:: ios_base :: iostate & err, std:: tm * t ) const ;
(2)
1) 公开成员函数,调用最终派生类的受保护虚成员函数 do_get_date
2) 从序列 [ beg , end ) 中连续读取字符,并使用此区域设置预期的默认格式解析出日历日期值。该格式由以下规则确定:
date_order() 格式
no_order "%m/%d/%y"
dmy "%d/%m/%y"
mdy "%m/%d/%y"
ymd "%y/%m/%d"
ydm "%y/%d/%m"
被函数 std::get_time() get() 以及 POSIX 函数 strptime() 所使用。
解析后的日期存储在参数 t 所指向的 std::tm 结构的对应字段中。
如果在读取到有效日期前到达结束迭代器,该函数将在 err 中设置 std::ios_base::eofbit 。如果遇到解析错误,该函数将在 err 中设置 std::ios_base::failbit

目录

参数

beg - 指向待解析序列起始位置的迭代器
end - 指向待解析序列结束位置后一位的迭代器
str - 函数在需要时用于获取本地化构件的流对象,例如使用 std::ctype 跳过空白字符或使用 std::collate 比较字符串
err - 流错误标志对象,由本函数修改以指示错误状态
t - 指向 std::tm 对象的指针,用于保存本函数调用的解析结果

返回值

指向 [ beg , end ) 范围内被识别为有效日期组成部分的最后一个字符之后位置的迭代器。

注释

对于默认日期格式中的字母成分(如有),此函数通常不区分大小写。

如果遇到解析错误,此函数的大多数实现会保持 * t 不变。

实现可能支持除标准要求之外的其它日期格式。

示例

#include <ctime>
#include <iostream>
#include <iterator>
#include <locale>
#include <sstream>
void try_get_date(const std::string& s)
{
    std::cout << "正在从'" << s
              << "'中解析日期,区域设置为" << std::locale().name() << '\n';
    std::istringstream str(s);
    std::ios_base::iostate err = std::ios_base::goodbit;
    std::tm t;
    const std::time_get<char>& facet = std::use_facet<std::time_get<char>>(str.getloc());
    std::istreambuf_iterator<char> ret = facet.get_date({str}, {}, str, err, &t);
    str.setstate(err);
    if (str)
    {
        std::cout << "日: " << t.tm_mday << ' '
                  << "月: " << t.tm_mon + 1 << ' '
                  << "年: " << t.tm_year + 1900 << '\n';
    }
    else
    {
        std::cout << "解析失败。未解析的字符串: ";
        std::copy(ret, {}, std::ostreambuf_iterator<char>(std::cout));
        std::cout << '\n';
    }
}
int main()
{
    std::locale::global(std::locale("en_US.utf8"));
    try_get_date("02/01/2013");
    try_get_date("02-01-2013");
    std::locale::global(std::locale("ja_JP.utf8"));
    try_get_date("2013年02月01日");
}

输出:

正在从'02/01/2013'中解析日期,区域设置为en_US.utf8
日: 1 月: 2 年: 2013
正在从'02-01-2013'中解析日期,区域设置为en_US.utf8
解析失败。未解析的字符串: -01-2013
正在从'2013年02月01日'中解析日期,区域设置为ja_JP.utf8
日: 1 月: 2 年: 2013

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 适用标准 发布时行为 正确行为
LWG 248 C++98 到达结束迭代器时未设置 eofbit 若未读取到有效日期则设置 eofbit
LWG 461 C++98 do_get_date 需要解析本地化日期表示 根据 date_order() 确定的格式进行解析

参见

(C++11)
解析指定格式的日期/时间值
(函数模板)