How to format date and time independent of locale

Explains how to format and display universal time, current time, date independent of locale settings.

In these code fragments, all output is purely numerical, date and time separators and formatting is fixed and locale independent.

To display the universal time and current local time implement code as follows:

  
TBuf<256> buffer;

    // Time in microseconds since 0 AD nominal Gregorian
TTime time;

    // year-month-day-hour-minute-second-microsecond
TDateTime dateTime;

    // Set and print Universal date/time
    // Get Universal time (= GMT)
time.UniversalTime();

    // Convert to fields
dateTime=time.DateTime();

    // Format universal time numerically
formatDateTime(buffer,dateTime);

    // Get current local time, taking daylight saving
    // into account, if in effect
time.HomeTime();

    // Convert to fields
dateTime=time.DateTime();

    // Format current local date/time numerically
formatDateTime(buffer,dateTime);

Here, the formatting is handled by the formatDateTime() function. This is implemented:

LOCAL_C void formatDateTime(TDes& aBuffer,TDateTime aDateTime)
    {
    _LIT(KFormatTxt,"%d %d %d %d:%d:%d.%d\n");
    aBuffer.Format(KFormatTxt,
                   aDateTime.Year(),
                   TInt(aDateTime.Month()+1), 
                       // Format the month as a TInt to preserve locale independence
                   aDateTime.Day()+1, 
                       // Day and month ranges begin at zero (0-30 and 0-11), 
                       // so add one when formatting
                   aDateTime.Hour(), aDateTime.Minute(), aDateTime.Second(),
                   aDateTime.MicroSecond()
                  );
    {

Notes

  • The TTime class is used for storing and manipulating times. As it stores a time value as a 64 bit integer, it needs to be converted into a TDateTime object, before it can be converted into formatted text.

  • TDateTime is the intermediary class for all input and output of dates and times by the user.

  • In the TDateTime class, the month is represented by a TMonth enumeration. The values of this enumeration are relative to zero. Similarly, the day is represented by a number whose value is zero for the first day in the month, one for the second day etc. Therefore, when formatting TDateTime values, as above, the integer representations of these fields must be incremented by one; they must be decremented by one when converting from human-readable values into TDateTime as the next example code fragment shows:

    
    ...
        // set date to 31st December 1996
        // set the date as if input from a user interface
    TInt year=1996;
    TInt month=12;
    TInt day=31;
    
    TInt error=dateTime.Set(year,TMonth(month-1),day-1,9,1,5,1000);
        // month and day values are zero-offset !
        // check that date/time are set ok
    User::LeaveIfError(dateTime.Set(year,TMonth(month-1),day-1,9,1,5,1000));
    ...