If you want to just specify the date in the corresponding line, you can use std::time_put<char> :
#include <locale> #include <ctime> #include <string> #include <sstream> std::string get_date_string(const std::time_t &input_time, const std::locale &loc){ std::tm * time = std::localtime ( &input_time ); // get time_put facet: const std::time_put<char>& tmput = std::use_facet <std::time_put<char> > (loc); std::stringstream s; s.imbue(loc);//set locale loc to the stream, no matter which global locale std::tm *my_time=std::localtime( &input_time ); tmput.put (s, s, ' ', my_time, 'x'); return s.str(); }
'x' says you only want a date. Other formats are possible: they are the same as for strftime . Now, after starting the program
int main(){ std::time_t timestamp; std::time( ×tamp ); std::cout<<"user settings: "<<get_date_string(timestamp, std::locale(""))<<"\n"; std::cout<<"C settings: "<<get_date_string(timestamp, std::locale::classic())<<"\n"; }
on my german car i see:
user settings: 13.01.2016 C settings: 01/13/16
If you are free to use boost, then this is a little easier with boost :: data_time :
#include <boost/date_time/gregorian/gregorian.hpp using namespace boost::gregorian; std::string get_date_string_boost(const date &d, const std::locale &loc){ date_facet* f = new date_facet("%x"); std::stringstream s; s.imbue(std::locale(loc, f)); s<<d; return s.str(); }
and now
int main(){ date d(2015, Jan, 13); std::cout<<"user settings with boost: "<<get_date_string_boost(d, std::locale(""))<<"\n"; std::cout<<"C settings with boost: "<<get_date_string_boost(d, std::locale::classic())<<"\n"; }
gives the same result as above.
If you want to explicitly specify the order of the dates, I donβt think you can ask for more than to know if it is ddmmyy (yy) or mmddyy (yy) or similar:
std::string date_order(const std::locale &loc){ std::time_get<char>::dateorder order = std::use_facet<std::time_get<char> >(loc).date_order(); switch (order) { case std::time_get<char>::dmy : return "dd/mm/yyyy"; case std::time_get<char>::mdy : return "mm/dd/yyyy"; case std::time_get<char>::ymd : return "yyyy/mm/dd"; case std::time_get<char>::ydm : return "yyyy/dd/mm"; default: return "no_order";
I do not know how it is distributed, on my machine it is "no_order", so do not expect too much information from it.