Writing and Reading Dates and Times - C++ Internationalization

C++ examples for Internationalization:Locale

Description

Writing and Reading Dates and Times

Demo Code

#include <iostream>
#include <ctime>
#include <locale>
#include <sstream>
#include <iterator>

using namespace std;

void translateDate(istream& in, ostream& out) {

   const time_get<char>& dateReader = use_facet<time_get<char> >(in.getloc());

   ios_base::iostate state = 0;//from   w ww.j av a 2  s  .  c  o m

   istreambuf_iterator<char> end;

   tm t; // Time struct (from <ctime>)

   dateReader.get_date(in, end, in, state, &t);

   if (state == 0 || state == ios_base::eofbit) {
      const time_put<char>& dateWriter = use_facet<time_put<char> >(out.getloc());

      char fmt[] = "%x";

      if (dateWriter.put(out, out, out.fill(), &t, &fmt[0], &fmt[2]).failed())
         cerr << "Unable to write to output stream.\n";
   } else {
      cerr << "Unable to read cin!\n";
   }
}

int main() {

   cin.imbue(locale("english"));
   cout.imbue(locale("german"));
   translateDate(cin, cout);
}

Result


Related Tutorials