c++ - C++ 11中日期字符串的工作日

标签 c++ date c++11

<分区>

我有这样的日期字符串:

"2015-11-27"

我想从中确定星期几。

这 ( live sample ) 是我使用 <ctime> 的方式:

int dayOfWeek(std::string date){
    int y, m, d; char c;
    std::stringstream(date) >> y >> c >> m >> c >> d;
    std::tm t = {0,0,0,d,m-1,y-1900};
    std::mktime(&t);
    return t.tm_wday;
}

但我想知道在 C++11 中是否有更规范的方法来解决这个问题?

最佳答案

您可以使用 std:get_time() 将这样的字符串转换为 std::tm

以下程序是在 http://en.cppreference.com/w/cpp/locale/time_get 上发布的程序的修改版本.

std::get_time() 的有效格式说明符可见于 http://en.cppreference.com/w/cpp/io/manip/get_time .

#include <iostream>
#include <sstream>
#include <string>
#include <locale>
#include <ctime>
#include <iomanip>

int main()
{
    std::string input = "2015-11-27";
    std::tm t = {};
    std::istringstream ss(input);
    ss >> std::get_time(&t, "%Y-%m-%d");
    std::mktime(&t);
    std::cout << std::asctime(&t);
}

http://ideone.com/xAEjsr 查看它的工作情况.

关于c++ - C++ 11中日期字符串的工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33952064/

相关文章:

c++ - 在模板参数中,哪些规则允许编译器推断数组的项数?

javascript - 在引导日期范围选择器中解析日期

c++ - 为什么初始化列表不能用作参数?

c++ - Eclipse juno c++调试错误193

c++ - unique_ptr 是否会控制它传递的任何指针,而不管它是如何创建的?

c++ - gsoap linux c++/struct 传递失败

python - 循环年份,同时跳过某些月份

python - 通过给出不是当前日期的引用日期作为参数来从文本中提取日期

c++ - 为什么我的线程永远不会结束

c++ - 需要帮助理解从 B.Stroustrup 的新书中摘录的这段文字