How to use Round-trip ("O", "o") Format Specifier in C#

Description

The "O" or "o" format preserves time zone information. Round-trip means the formatted string can be parsed back to a date time value.

The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values.

Example

The following example uses the "o" format specifier to display a DateTime and a DateTimeOffset value on a system in the U.S. Pacific Time zone.


/*from   w  ww  . ja v a2  s.c  o  m*/
using System;

class MainClass
{

  public static void Main()
  {
        DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
        DateTimeOffset dateOffset = new DateTimeOffset(date1, TimeZoneInfo.Local.GetUtcOffset(date1));
        Console.WriteLine(date1.ToString("o"));
        Console.WriteLine(dateOffset.ToString("o"));

  }

}

The following example uses the "o" format specifier to create a formatted string, and then restores the original date and time value by calling a date and time Parse method.


/*w  ww . j a  v  a 2  s.c  om*/
using System;
using System.Globalization;
class MainClass
{

    public static void Main()
    {
        // Round-trip DateTime values.
        DateTime originalDate, newDate;
        string dateString;
        // Round-trip a local time.
        originalDate =
           DateTime.SpecifyKind(new DateTime(2008, 4, 10, 6, 30, 0), DateTimeKind.Local);
        dateString = originalDate.ToString("o");
        newDate = DateTime.Parse(dateString, null, DateTimeStyles.RoundtripKind);
        Console.WriteLine("Round-tripped {0} {1} to {2} {3}.",
                      originalDate, originalDate.Kind, newDate, newDate.Kind);

    }

}




















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