< C++ .NET Formatting 8 | Main | C++ .NET Formatting Supp 1 >


 

 

Playing With C++ .NET Formatting 9

 

 

 

 

 

The following is the topic available in this part.

  1. DateTimeFormatInfo Class Example

 

 

DateTimeFormatInfo Class Example

 

This class defines how DateTime values are formatted and displayed, depending on the culture. The namespace and assembly are:

Namespace: System.Globalization

Assembly: mscorlib (in mscorlib.dll)

This class contains information, such as date patterns, time patterns, and AM/PM designators. To create a DateTimeFormatInfo for a specific culture, create a CultureInfo for that culture and retrieve the CultureInfo.DateTimeFormat property. To create a DateTimeFormatInfo for the culture of the current thread, use the CurrentInfo property. To create a DateTimeFormatInfo for the invariant culture, use the InvariantInfo property for a read-only version, or use the DateTimeFormatInfo constructor for a writable version. It is not possible to create a DateTimeFormatInfo for a neutral culture.

The user might choose to override some of the values associated with the current culture of Windows through Regional and Language Options (or Regional Options or Regional Settings) in Control Panel. For example, the user might choose to display the date in a different format or to use a currency other than the default for the culture. If the CultureInfo.UseUserOverride property is set to true, the properties of the CultureInfo.DateTimeFormat instance, the CultureInfo.NumberFormat instance, and the CultureInfo.TextInfo instance are also retrieved from the user settings. If the user settings are incompatible with the culture associated with the CultureInfo (for example, if the selected calendar is not one of the OptionalCalendars), the results of the methods and the values of the properties are undefined. DateTime values are formatted using standard or custom patterns stored in the properties of a DateTimeFormatInfo. The standard patterns can be replaced with custom patterns by setting the associated properties of a writable DateTimeFormatInfo. To determine if a DateTimeFormatInfo is writable, use the IsReadOnly property. The following table lists the standard format characters for each standard pattern and the associated DateTimeFormatInfo property that can be set to modify the standard pattern. The format characters are case-sensitive; for example, 'g' and 'G' represent slightly different patterns.

 

Format Character

Associated Property / Description

d

ShortDatePattern

D

LongDatePattern

f

Full date and time (long date and short time)

F

FullDateTimePattern (long date and long time)

g

General (short date and short time)

G

General (short date and long time)

m, M

MonthDayPattern

r, R

RFC1123Pattern

s

SortableDateTimePattern (based on ISO 8601) using local time

t

ShortTimePattern

T

LongTimePattern

u

UniversalSortableDateTimePattern using the format for universal time display

U

Full date and time (long date and long time) using universal time

y, Y

YearMonthPattern

 

Table 9

 

The following table lists the patterns that can be combined to construct custom patterns. The patterns are case-sensitive; for example, "MM" is recognized, but "mm" is not. If the custom pattern contains white-space characters or characters enclosed in single quotation marks, the output string will also contain those characters. Characters not defined as part of a format pattern or as format characters are reproduced literally.

 

Format Pattern

Description

d, %d

The day of the month. Single-digit days will not have a leading zero. Specify "%d" if the format pattern is not combined with other format patterns.

dd

The day of the month. Single-digit days will have a leading zero.

ddd

The abbreviated name of the day of the week, as defined in AbbreviatedDayNames.

dddd

The full name of the day of the week, as defined in DayNames.

M, %M

The numeric month. Single-digit months will not have a leading zero. Specify "%M" if the format pattern is not combined with other format patterns.

MM

The numeric month. Single-digit months will have a leading zero.

MMM

The abbreviated name of the month, as defined in AbbreviatedMonthNames.

MMMM

The full name of the month, as defined in MonthNames.

y, %y

The year without the century. If the year without the century is less than 10, the year is displayed with no leading zero. Specify "%y" if the format pattern is not combined with other format patterns.

yy

The year without the century. If the year without the century is less than 10, the year is displayed with a leading zero.

yyyy

The year in four digits, including the century.

gg

The period or era. This pattern is ignored if the date to be formatted does not have an associated period or era string.

h, %h

The hour in a 12-hour clock. Single-digit hours will not have a leading zero. Specify "%h" if the format pattern is not combined with other format patterns.

hh

The hour in a 12-hour clock. Single-digit hours will have a leading zero.

H, %H

The hour in a 24-hour clock. Single-digit hours will not have a leading zero. Specify "%H" if the format pattern is not combined with other format patterns.

HH

The hour in a 24-hour clock. Single-digit hours will have a leading zero.

m, %m

The minute. Single-digit minutes will not have a leading zero. Specify "%m" if the format pattern is not combined with other format patterns.

mm

The minute. Single-digit minutes will have a leading zero.

s, %s

The second. Single-digit seconds will not have a leading zero. Specify "%s" if the format pattern is not combined with other format patterns.

ss

The second. Single-digit seconds will have a leading zero.

f, %f

The fraction of a second in single-digit precision. The remaining digits are truncated. Specify "%f" if the format pattern is not combined with other format patterns.

ff

The fraction of a second in double-digit precision. The remaining digits are truncated.

fff

The fraction of a second in three-digit precision. The remaining digits are truncated.

ffff

The fraction of a second in four-digit precision. The remaining digits are truncated.

fffff

The fraction of a second in five-digit precision. The remaining digits are truncated.

ffffff

The fraction of a second in six-digit precision. The remaining digits are truncated.

fffffff

The fraction of a second in seven-digit precision. The remaining digits are truncated.

F, %F

Displays the most significant digit of the seconds fraction. Nothing is displayed if the digit is zero. Specify "%F" if the format pattern is not combined with other format patterns.

FF

Displays the two most significant digits of the seconds fraction. However, trailing zeros, or two zero digits, are not displayed.

FFF

Displays the three most significant digits of the seconds fraction. However, trailing zeros, or three zero digits, are not displayed.

FFFF

Displays the four most significant digits of the seconds fraction. However, trailing zeros, or four zero digits, are not displayed.

FFFFF

Displays the five most significant digits of the seconds fraction. However, trailing zeros, or five zero digits, are not displayed.

FFFFFF

Displays the six most significant digits of the seconds fraction. However, trailing zeros, or six zero digits, are not displayed.

FFFFFFF

Displays the seven most significant digits of the seconds fraction. However, trailing zeros, or seven zero digits, are not displayed.

t, %t

The first character in the AM/PM designator defined in AMDesignator or PMDesignator, if any. Specify "%t" if the format pattern is not combined with other format patterns.

tt

The AM/PM designator defined in AMDesignator or PMDesignator, if any.

z, %z

The time zone offset ("+" or "-" followed by the hour only). Single-digit hours will not have a leading zero. For example, Pacific Standard Time is "-8". Specify "%z" if the format pattern is not combined with other format patterns.

zz

The time zone offset ("+" or "-" followed by the hour only). Single-digit hours will have a leading zero. For example, Pacific Standard Time is "-08".

zzz

The full time zone offset ("+" or "-" followed by the hour and minutes). Single-digit hours and minutes will have leading zeros. For example, Pacific Standard Time is "-08:00".

:

The default time separator defined in TimeSeparator.

/

The default date separator defined in DateSeparator.

%c

Where c is a format pattern if used alone. That is, to use format pattern "d", "f", "F", "h", "m", "s", "t", "y", "z", "H", or "M" by itself, specify "%d", "%f", "%F", "%h", "%m", "%s", "%t", "%y", "%z", "%H", or "%M". The "%" character can be omitted if the format pattern is combined with literal characters or other format patterns.

\c

Where c is any character. Displays the character literally. To display the backslash character, use "\\".

 

Table 10

 

Only format patterns listed in the second table above can be used to create custom patterns; standard format characters listed in the first table cannot be used to create custom patterns. Custom patterns are at least two characters long; for example:

  1. DateTime.ToString("d") returns the DateTime value; "d" is the standard short date pattern.

  2. DateTime.ToString("%d") returns the day of the month; "%d" is a custom pattern.

  3. DateTime.ToString("d ") returns the day of the month followed by a white-space character; "d " is a custom pattern.

A DateTimeFormatInfo or a NumberFormatInfo can be created only for the invariant culture or for specific cultures, not for neutral cultures. For more information about the invariant culture, specific cultures, and neutral cultures. This class implements the ICloneable interface to enable duplication of DateTimeFormatInfo objects. It also implements IFormatProvider to supply formatting information to applications. The following code example converts a DateTime value to a String with the ToString method, using an IFormatProvider object.

// testprog.cpp : main project file.

// Example of the Convert::ToString(DateTime) and

// Convert::ToString(DateTime, IFormatProvider*) methods.

#include "stdafx.h"

 

using namespace System;

using namespace System::Globalization;

 

#define null (Object^)0

 

void DisplayDateNCultureName(DateTime testDate, String^ cultureName)

{

   // Create the CultureInfo object for the specified culture,

   // and use it as the IFormatProvider when converting the date.

   CultureInfo^ culture = gcnew CultureInfo(cultureName);

   String^ dateString = Convert::ToString(testDate, culture);

   // Bracket the culture name, and display the name and date.

   Console::WriteLine("   {0,-12}{1}", String::Concat("[", cultureName, "]"), dateString);

}

 

int main()

{

   // Specify the date to be formatted under various cultures.

   DateTime tDate = DateTime(2003,4,15,20,30,40,333);

   Console::WriteLine("This example of \n"

   "   Convert::ToString(DateTime) and \n"

   "   Convert::ToString(DateTime, IFormatProvider*)\n"

   "generates the following output. It creates "

   "CultureInfo objects \nfor several cultures "

   "and formats a DateTime value with each.\n");

   // Format the date without an IFormatProvider.

   Console::WriteLine("   {0,-12}{1}", null, "No IFormatProvider");

   Console::WriteLine("   {0,-12}{1}", null, "------------------");

   Console::WriteLine("   {0,-12}{1}\n", String::Concat("[", CultureInfo::CurrentCulture->Name, "]" ), Convert::ToString(tDate));

   // Format the date with IFormatProvider for several cultures.

   Console::WriteLine("   {0,-12}{1}", "Culture", "With IFormatProvider");

   Console::WriteLine("   {0,-12}{1}", "-------", "--------------------");

   DisplayDateNCultureName(tDate, "");

   DisplayDateNCultureName(tDate, "nl-NL");

   DisplayDateNCultureName(tDate, "ru-RU");

   DisplayDateNCultureName(tDate, "ur-PK");

   DisplayDateNCultureName(tDate, "en-US");

   DisplayDateNCultureName(tDate, "es-AR");

   DisplayDateNCultureName(tDate, "fr-FR");

   DisplayDateNCultureName(tDate, "ar-EG");

   DisplayDateNCultureName(tDate, "zh-CN");

   DisplayDateNCultureName(tDate, "hi-IN");

   DisplayDateNCultureName(tDate, "hi-IN");

   DisplayDateNCultureName(tDate, "ja-JP");

   return 0;

}

 

Output:

 

 

 

 

 

 

C++ .NET formatting - code example converts a DateTime value to a String with the ToString method, using an IFormatProvider object

 

The following code example illustrates the use of a class that implements the IFormatProvider interface and the GetFormat method. The AnyRadix class supports the "Ra" formatting code and converts an Int64 value to a string of any specified radix between 2 and 36. GetFormat returns a reference to itself if the Type parameter refers to a class that implements ICustomFormatter; otherwise, GetFormat returns a null reference (Nothing in Visual Basic).

// testprog.cpp : main project file.

// Sample for the IFormatProvider interface and

// the IFormatProvider::GetFormat(Type*) method.

#include "stdafx.h"

 

using namespace System;

 

// This class implements the "Ra" formatting code. An instance of this

// class should be passed to methods requiring an IFormatProvider.

ref class AnyRadix: public IFormatProvider, public ICustomFormatter

{

  private:

    static Object^ null = nullptr;

    // The value to be formatted is returned as a signed string

    // of digits from the rDigits array.

    static String^ radixCode = "Ra";

    static array<Char>^rDigits = {'0','1','2','3','4','5','6','7','8',

     '9','A','B','C','D','E','F','G','H','I','J','K','L','M','N',

     'O','P','Q','R','S','T','U','V','W','X','Y','Z'};

  public:

    // This method returns an object that implements

    // ICustomFormatter to do the formatting.

    virtual Object^ GetFormat(Type^ argType)

    {

        // Here, the same object (this) is returned, but it would

        // be possible to return an object of a different type.

        if (argType == ICustomFormatter::typeid)

           return this;

        else

           return null;

    }

    // This method does the formatting only

    // if it recognizes the format codes.

    virtual String^ Format(String^ formatString, Object^ argToBeFormatted, IFormatProvider^ provider)

    {

       // If no format string is provided or the format string cannot

       // be handled, use IFormattable or standard string processing.

       if (formatString == null || !formatString->Trim()->StartsWith(radixCode))

       {

         if (dynamic_cast<IFormattable^>(argToBeFormatted) != nullptr)

            return static_cast<IFormattable^>(argToBeFormatted)->ToString(formatString, provider);

         else

            return argToBeFormatted->ToString();

       }

       // The formatting is handled here.

       int digitIndex = 0;

       __int64 radix;

       __int64 longToBeFormatted;

       __int64 longPositive;

       array<Char>^outDigits = gcnew array<Char>(64);

       // Extract the radix from the format string.

       formatString = formatString->Replace(radixCode, "");

       try

       {

         radix = Convert::ToInt64(formatString);

       }

       catch (Exception^ ex)

       {

       throw gcnew ArgumentException(String::Format("The radix \"{0}\" is invalid.\n", formatString ),ex);

       }

       // Verify that the radix is in the proper range.

       if (radix < 2 || radix > 36)

          throw gcnew ArgumentException(String::Format("The radix \"{0}\" is not in the range 2..36.", formatString));

       // Verify that the argument can be converted to a long integer.

       try

       {

          longToBeFormatted =  *static_cast<__int64^>(argToBeFormatted);

       }

       catch (Exception^ ex)

       {

          throw gcnew ArgumentException(String::Format("The argument \"{0}\" cannot be "

                "converted to an integer value.", argToBeFormatted),ex);

       }

       // Extract the magnitude for conversion.

       longPositive = Math::Abs(longToBeFormatted);

       // Convert the magnitude to a digit string.

       for (digitIndex = 0; longPositive != 0 && digitIndex <= 64; digitIndex++)

       {

          outDigits[outDigits->Length - digitIndex - 1] = rDigits[longPositive % radix];

          longPositive /= radix;

       }

       // Add a minus sign if the argument is negative.

       if (longToBeFormatted < 0)

          outDigits[outDigits->Length - digitIndex++ - 1] = '-';

       return gcnew String(outDigits,outDigits->Length - digitIndex, digitIndex);

   }

};

 

void ConvertToAnyRadix(Object^ argToConvert, String^ formatStr)

{

      AnyRadix^ provider = gcnew AnyRadix;

      String^ messageStr = String::Format("{{0:{0}}}", formatStr);

      // Write the first part of the output line.

      Console::Write("{0,18}  {1,-6}", argToConvert, formatStr);

      // Convert the specified argument using the specified format.

      try

      {

         array<Object^>^argArray = {argToConvert};

         Console::WriteLine(String::Format(provider, messageStr, argArray));

      }

      catch (Exception^ ex)

      {

         // Display the exception without the stack trace.

         int lineEnd = ex->ToString()->IndexOf('\n');

         Console::WriteLine("{0}\n", ex->ToString()->Substring(0, lineEnd));

      }

}

 

int main()

{

      __int64 twoToThe32 = 4294967296;

      __int64 fifteenNines = 999999999999999;

      Console::WriteLine("This example of the IFormatProvider interface \n"

            "and the IFormatProvider::GetFormat(Type*) method "

            "\ngenerates the following output.\n");

      Console::WriteLine("{0,18} Format Result", "Number");

      Console::WriteLine("{0,18} ------ ------", "------");

      // These are valid conversions.

      ConvertToAnyRadix(twoToThe32, "Ra2");

      ConvertToAnyRadix(twoToThe32, "Ra5");

      ConvertToAnyRadix(twoToThe32, "Ra16");

      ConvertToAnyRadix(twoToThe32, "Ra23");

      ConvertToAnyRadix(twoToThe32, "Ra36");

      ConvertToAnyRadix(fifteenNines, "Ra2");

      ConvertToAnyRadix(fifteenNines, "Ra3");

      ConvertToAnyRadix(fifteenNines, "Ra8");

      ConvertToAnyRadix(fifteenNines, "Ra11");

      ConvertToAnyRadix(fifteenNines, "Ra16");

      ConvertToAnyRadix(fifteenNines, "Ra23");

      ConvertToAnyRadix(fifteenNines, "Ra36");

      ConvertToAnyRadix(fifteenNines, "E16");

      ConvertToAnyRadix(fifteenNines, "");

      // These are error conditions.

      ConvertToAnyRadix(fifteenNines, "Ra37");

      ConvertToAnyRadix("ABCDEFGHIJKLM", "Ra16");

      return 0;

}

 

Output:

 

 

 

 

 

 

 

---------------------------------------

C++ .NEt formatting - code example that illustrates the use of a class that implements the IFormatProvider interface and the GetFormat method

 

 

 

 

 

Part 1 | Part 2 | Part 3 | Part 4 | Part 5 | Part 6 | Part 7 | Part 8 | Part 9


< C++ .NET Formatting 8 | Main | C++ .NET Formatting Supp 1 >