Convert DateTime to string representation using the specified format.

in CSharp

Description

The following code shows how to convert DateTime to string representation using the specified format.

Example


using System;//from   w ww. ja v  a2s  . c om
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      DateTime date1 = new DateTime(1550, 7, 21);
      CultureInfo dft;
      CultureInfo heIL = new CultureInfo("he-IL");
      heIL.DateTimeFormat.Calendar = new HebrewCalendar();

      // Change current culture to he-IL.
      dft = Thread.CurrentThread.CurrentCulture;
      Thread.CurrentThread.CurrentCulture = heIL;

      // Display the date using the current culture's calendar.             
      try {
         Console.WriteLine(date1.ToString("G"));
      }   
      catch (ArgumentOutOfRangeException) {
         Console.WriteLine("{0} is earlier than {1} or later than {2}", 
                           date1.ToString("d", CultureInfo.InvariantCulture), 
                           heIL.DateTimeFormat.Calendar.MinSupportedDateTime.ToString("d",  
                           CultureInfo.InvariantCulture),  
                           heIL.DateTimeFormat.Calendar.MaxSupportedDateTime.ToString("d", 
                           CultureInfo.InvariantCulture)); 
      }

      // Restore the default culture.
      Thread.CurrentThread.CurrentCulture = dft;
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var