Parse a string in UTC to DateTime in CSharp

Description

The following code shows how to parse a string in UTC to DateTime.

Example


//from   ww  w.ja  v a 2  s  .com
using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      CultureInfo enUS = new CultureInfo("en-US"); 
      string dateString;
      DateTime dateValue;

      // Parse a string represengting UTC.
      dateString = "2008-06-11T16:11:20.0904778Z";
      try {
         dateValue = DateTime.ParseExact(dateString, "o", CultureInfo.InvariantCulture, 
                                     DateTimeStyles.None);
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
                           dateValue.Kind);
      }                           
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      }
      try {
         dateValue = DateTime.ParseExact(dateString, "o", CultureInfo.InvariantCulture, 
                                     DateTimeStyles.RoundtripKind);
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
                           dateValue.Kind);
      }                           
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      }
   }
}

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