Output time and date using the time_put facets in both English and German. - C++ Internationalization

C++ examples for Internationalization:Time

Introduction

The tm structure is defined in <ctime> and is inherited from C.

It is shown here:

struct tm {
   int tm_sec;  // seconds, 0-61
   int tm_min;  // minutes, 0-59
   int tm_hour; // hours, 0-23
   int tm_mday; // day of the month, 1-31
   int tm_mon;  // months since Jan, 0-11
   int tm_year; // years from 1900
   int tm_wday; // days since Sunday, 0-6
   int tm_yday; // days since Jan 1, 0-365
   int tm_isdst // Daylight Saving Time indicator
}

Demo Code

#include <iostream>
#include <locale>
#include <cstring>
#include <ctime>
using namespace std;
int main()/*  w w w.j  a  v a  2  s  . c  o m*/
{
   // Obtain the current system time.
   time_t t = time(NULL);
   tm *cur_time = localtime(&t);
   // Create US and German locales.
   locale usloc("English_US");
   locale gloc("German_Germany");
   // Set the locale to US and get the time_put facet for US.
   cout.imbue(usloc);
   const time_put<char> &us_time =
   use_facet<time_put<char> >(cout.getloc());
   // %c specifies the standard time and date pattern.
   char *std_pat = "%c";
   char *std_pat_end = std_pat + strlen(std_pat);
   // The following custom pattern displays hours and minutes followed by the date.
   char *custom_pat = "%A %B %d, %Y %H:%M";
   char *custom_pat_end = custom_pat + strlen(custom_pat);
   cout << "Standard US time and date format: ";
   us_time.put(cout, cout, ' ', cur_time, std_pat, std_pat_end);
   cout << endl;
   cout << "Custom US time and date format: ";
   us_time.put(cout, cout, ' ', cur_time, custom_pat, custom_pat_end);
   cout << "\n\n";
   // Set the locale to Germany and get the time_put facet for Germany.
   cout.imbue(gloc);
   const time_put<char> &g_time =
   use_facet<time_put<char> >(cout.getloc());
   cout << "Standard German time and date format: ";
   g_time.put(cout, cout, ' ', cur_time, std_pat, std_pat_end);
   cout << endl;
   cout << "Custom German time and date format: ";
   g_time.put(cout, cout, ' ', cur_time, custom_pat, custom_pat_end);
   cout << endl;
   return 0;
}

Result


Related Tutorials