1

I have date strings like this:

"2015-11-27"

and from them I want to determine the day of week.

This (live sample) is how I would do it using <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;
}

but I'm wondering whether there is a more canonical way to go about this in C++11?

Museful
  • 6,711
  • 5
  • 42
  • 68

1 Answers1

3

You can use std:get_time() to translate such a string to a std::tm.

The following program is a modified version of the program published at http://en.cppreference.com/w/cpp/locale/time_get.

The valid format specifiers for std::get_time() can be seen at 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);
}

See it working at http://ideone.com/xAEjsr.

R Sahu
  • 204,454
  • 14
  • 159
  • 270