2015-11-27 30 views
1

我有日期字符串是這樣的:平日在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?

+1

@SuperBiasedMan更好嗎? – Museful

回答

3

您可以使用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

+1

** Sun ** Nov 27 00:00:00 2015? ([Coliru](http://coliru.stacked-crooked.com/a/e9014081bd440ec2)) –

+0

@decltype_auto,'std :: tm t = {};'不是最好的主意。垃圾進垃圾出。 –

+1

但是 - 如何做到這一點?區域設置imbue的東西? –