How to use Universal Sortable ("u") Format Specifier in C# for Date and Time

Description

The "u" format is defined by the DateTimeFormatInfo.UniversalSortableDateTimePattern property. The custom format string is "yyyy'-'MM'-'dd HH':'mm':'ss'Z'".

We have to convert the date and time value to UTC before formatting it. To perform this conversion, DateTime values can call the DateTime.ToUniversalTime method, and DateTimeOffset values can call the ToUniversalTime method.

Example

The following example uses the "u" format specifier to display a date and time value.


// ww  w .  ja  va2  s . c o m
using System;

class MainClass
{

  public static void Main()
  {
        DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
        Console.WriteLine(date1.ToUniversalTime().ToString("u"));
        // Displays 2008-04-10 13:30:00Z   
  }

}

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