5

到目前为止,我能够获得当前的语言环境,但我想获得该特定语言环境的日期格式。这可以用标准库来完成吗?

#include <locale>

int _tmain(int argc, _TCHAR* argv[])
{
   // Print the current locale
    std::cout << std::locale("").name().c_str() << "\n";

    // TODO: get the locale's date pattern, example for US it's (mm/dd/yyyy)
    std::cout << "date pattern:  \n";
}
4

1 回答 1

4

如果您只想将日期转换为相应的字符串,您可以使用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'说你只想要日期。其他格式也是可能的 - 它们与strftime相同。现在,运行程序后

int main(){

      std::time_t timestamp;
      std::time( &timestamp );

      std::cout<<"user settings: "<<get_date_string(timestamp, std::locale(""))<<"\n";
      std::cout<<"C settings: "<<get_date_string(timestamp, std::locale::classic())<<"\n";
}

在我的德国机器上,我看到:

user settings: 13.01.2016
C settings: 01/13/16

如果您可以自由使用 boost,那么使用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();
}

现在

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";

}

产生与上述相同的结果。

如果您想明确知道日期顺序,我认为您只能要求知道它是 ddmmyy(yy) 还是 mmddyy(yy) 或类似的:

  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";//case std::time_get<char>::no_order
      }

  }

我不知道分布情况如何,在我的机器上它是“no_order”,所以不要期望从中得到太多信息。

于 2016-01-12T22:35:00.873 回答