Instantiating a DateTimeOffset object
The DateTimeOffset structure offers a number of ways to create new DateTimeOffset values. Many of them correspond directly to the methods available for instantiating new DateTime values, with enhancements that allow you to specify the date and time value's offset from Coordinated Universal Time (UTC). In particular, you can instantiate a DateTimeOffset value in the following ways:
By using a date and time literal.
By calling a DateTimeOffset constructor.
By implicitly converting a value to DateTimeOffset value.
By parsing the string representation of a date and time.
This topic provides greater detail and code examples that illustrate these methods of instantiating new DateTimeOffset values.
Date and time literals
For languages that support it, one of the most common ways to instantiate a DateTime value is to provide the date and time as a hard-coded literal value. For example, the following Visual Basic code creates a DateTime object whose value is May 1, 2008, at 8:06:32 AM.
Dim literalDate1 As Date = #05/01/2008 8:06:32 AM#
Console.WriteLine(literalDate1.ToString())
' Displays:
' 5/1/2008 8:06:32 AM
DateTimeOffset values can also be initialized using date and time literals when using languages that support DateTime literals. For example, the following Visual Basic code creates a DateTimeOffset object.
Dim literalDate As DateTimeOffset = #05/01/2008 8:06:32 AM#
Console.WriteLine(literalDate.ToString())
' Displays:
' 5/1/2008 8:06:32 AM -07:00
As the console output shows, the DateTimeOffset value created in this way is assigned the offset of the local time zone. This means that a DateTimeOffset value assigned using a character literal does not identify a single point of time if the code is run on different computers.
DateTimeOffset constructors
The DateTimeOffset type defines six constructors. Four of them correspond directly to DateTime constructors, with an additional parameter of type TimeSpan that defines the date and time's offset from UTC. These allow you to define a DateTimeOffset value based on the value of its individual date and time components. For example, the following code uses these four constructors to instantiate DateTimeOffset objects with identical values of 5/1/2008 8:06:32 +01:00.
DateTimeOffset dateAndTime;
// Instantiate date and time using years, months, days,
// hours, minutes, and seconds
dateAndTime = new DateTimeOffset(2008, 5, 1, 8, 6, 32,
new TimeSpan(1, 0, 0));
Console.WriteLine(dateAndTime);
// Instantiate date and time using years, months, days,
// hours, minutes, seconds, and milliseconds
dateAndTime = new DateTimeOffset(2008, 5, 1, 8, 6, 32, 545,
new TimeSpan(1, 0, 0));
Console.WriteLine("{0} {1}", dateAndTime.ToString("G"),
dateAndTime.ToString("zzz"));
// Instantiate date and time using Persian calendar with years,
// months, days, hours, minutes, seconds, and milliseconds
dateAndTime = new DateTimeOffset(1387, 2, 12, 8, 6, 32, 545,
new PersianCalendar(),
new TimeSpan(1, 0, 0));
// Note that the console output displays the date in the Gregorian
// calendar, not the Persian calendar.
Console.WriteLine("{0} {1}", dateAndTime.ToString("G"),
dateAndTime.ToString("zzz"));
// Instantiate date and time using number of ticks
// 05/01/2008 8:06:32 AM is 633,452,259,920,000,000 ticks
dateAndTime = new DateTimeOffset(633452259920000000, new TimeSpan(1, 0, 0));
Console.WriteLine(dateAndTime);
// The example displays the following output to the console:
// 5/1/2008 8:06:32 AM +01:00
// 5/1/2008 8:06:32 AM +01:00
// 5/1/2008 8:06:32 AM +01:00
// 5/1/2008 8:06:32 AM +01:00
Dim dateAndTime As DateTimeOffset
' Instantiate date and time using years, months, days,
' hours, minutes, and seconds
dateAndTime = New DateTimeOffset(2008, 5, 1, 8, 6, 32, _
New TimeSpan(1, 0, 0))
Console.WriteLine(dateAndTime)
' Instantiate date and time using years, months, days,
' hours, minutes, seconds, and milliseconds
dateAndTime = New DateTimeOffset(2008, 5, 1, 8, 6, 32, 545, _
New TimeSpan(1, 0, 0))
Console.WriteLine("{0} {1}", dateAndTime.ToString("G"), _
dateAndTime.ToString("zzz"))
' Instantiate date and time using Persian calendar with years,
' months, days, hours, minutes, seconds, and milliseconds
dateAndTime = New DateTimeOffset(1387, 2, 12, 8, 6, 32, 545, New PersianCalendar, New TimeSpan(1, 0, 0))
' Note that the console output displays the date in the Gregorian
' calendar, not the Persian calendar.
Console.WriteLine("{0} {1}", dateAndTime.ToString("G"), _
dateAndTime.ToString("zzz"))
' Instantiate date and time using number of ticks
' 05/01/2008 8:06:32 AM is 633,452,259,920,000,000 ticks
dateAndTime = New DateTimeOffset(633452259920000000, New TimeSpan(1, 0, 0))
Console.WriteLine(dateAndTime)
' The example displays the following output to the console:
' 5/1/2008 8:06:32 AM +01:00
' 5/1/2008 8:06:32 AM +01:00
' 5/1/2008 8:06:32 AM +01:00
' 5/1/2008 8:06:32 AM +01:00
Note that, when the value of the DateTimeOffset object instantiated using a PersianCalendar object as one of the arguments to its constructor is displayed to the console, it is expressed as a date in the Gregorian rather than the Persian calendar. To output a date using the Persian calendar, see the example in the PersianCalendar topic.
The other two constructors create a DateTimeOffset object from a DateTime value. The first of these has a single parameter, the DateTime value to convert to a DateTimeOffset value. The offset of the resulting DateTimeOffset value depends on the Kind property of the constructor's single parameter. If its value is DateTimeKind.Utc, the offset is set equal to TimeSpan.Zero. Otherwise, its offset is set equal to that of the local time zone. The following example illustrates the use of this constructor to instantiate DateTimeOffset objects representing UTC and the local time zone:
// Declare date; Kind property is DateTimeKind.Unspecified
DateTime sourceDate = new DateTime(2008, 5, 1, 8, 30, 0);
DateTimeOffset targetTime;
// Instantiate a DateTimeOffset value from a UTC time
DateTime utcTime = DateTime.SpecifyKind(sourceDate, DateTimeKind.Utc);
targetTime = new DateTimeOffset(utcTime);
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM +00:00
// Because the Kind property is DateTimeKind.Utc,
// the offset is TimeSpan.Zero.
// Instantiate a DateTimeOffset value from a UTC time with a zero offset
targetTime = new DateTimeOffset(utcTime, TimeSpan.Zero);
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM +00:00
// Because the Kind property is DateTimeKind.Utc,
// the call to the constructor succeeds
// Instantiate a DateTimeOffset value from a UTC time with a negative offset
try
{
targetTime = new DateTimeOffset(utcTime, new TimeSpan(-2, 0, 0));
Console.WriteLine(targetTime);
}
catch (ArgumentException)
{
Console.WriteLine("Attempt to create DateTimeOffset value from {0} failed.",
targetTime);
}
// Throws exception and displays the following to the console:
// Attempt to create DateTimeOffset value from 5/1/2008 8:30:00 AM +00:00 failed.
// Instantiate a DateTimeOffset value from a local time
DateTime localTime = DateTime.SpecifyKind(sourceDate, DateTimeKind.Local);
targetTime = new DateTimeOffset(localTime);
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM -07:00
// Because the Kind property is DateTimeKind.Local,
// the offset is that of the local time zone.
// Instantiate a DateTimeOffset value from an unspecified time
targetTime = new DateTimeOffset(sourceDate);
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM -07:00
// Because the Kind property is DateTimeKind.Unspecified,
// the offset is that of the local time zone.
' Declare date; Kind property is DateTimeKind.Unspecified
Dim sourceDate As Date = #5/1/2008 8:30 AM#
Dim targetTime As DateTimeOffset
' Instantiate a DateTimeOffset value from a UTC time
Dim utcTime As Date = Date.SpecifyKind(sourceDate, DateTimeKind.Utc)
targetTime = New DateTimeOffset(utcTime)
Console.WriteLine(targetTime)
' Displays 5/1/2008 8:30:00 AM +00:00
' Because the Kind property is DateTimeKind.Utc,
' the offset is TimeSpan.Zero.
' Instantiate a DateTimeOffset value from a local time
Dim localTime As Date = Date.SpecifyKind(sourceDate, DateTimeKind.Local)
targetTime = New DateTimeOffset(localTime)
Console.WriteLine(targetTime)
' Displays 5/1/2008 8:30:00 AM -07:00
' Because the Kind property is DateTimeKind.Local,
' the offset is that of the local time zone.
' Instantiate a DateTimeOffset value from an unspecified time
targetTime = New DateTimeOffset(sourceDate)
Console.WriteLine(targetTime)
' Displays 5/1/2008 8:30:00 AM -07:00
' Because the Kind property is DateTimeKind.Unspecified,
' the offset is that of the local time zone.
'
Note
Calling the overload of the DateTimeOffset constructor that has a single DateTime parameter is equivalent to performing an implicit conversion of a DateTime value to a DateTimeOffset value.
The second constructor that creates a DateTimeOffset object from a DateTime value has two parameters: the DateTime value to convert, and a TimeSpan value representing the date and time's offset from UTC. This offset value must correspond to the Kind property of the constructor's first parameter or an ArgumentException is thrown. If the Kind property of the first parameter is DateTimeKind.Utc, the value of the second parameter must be TimeSpan.Zero. If the Kind property of the first parameter is DateTimeKind.Local, the value of the second parameter must be the offset of the local system's time zone. If the Kind property of the first parameter is DateTimeKind.Unspecified, the offset can be any valid value. The following code illustrates calls to this constructor to convert DateTime to DateTimeOffset values.
DateTime sourceDate = new DateTime(2008, 5, 1, 8, 30, 0);
DateTimeOffset targetTime;
// Instantiate a DateTimeOffset value from a UTC time with a zero offset.
DateTime utcTime = DateTime.SpecifyKind(sourceDate, DateTimeKind.Utc);
targetTime = new DateTimeOffset(utcTime, TimeSpan.Zero);
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM +00:00
// Because the Kind property is DateTimeKind.Utc,
// the call to the constructor succeeds
// Instantiate a DateTimeOffset value from a UTC time with a non-zero offset.
try
{
targetTime = new DateTimeOffset(utcTime, new TimeSpan(-2, 0, 0));
Console.WriteLine(targetTime);
}
catch (ArgumentException)
{
Console.WriteLine("Attempt to create DateTimeOffset value from {0} failed.",
utcTime);
}
// Throws exception and displays the following to the console:
// Attempt to create DateTimeOffset value from 5/1/2008 8:30:00 AM failed.
// Instantiate a DateTimeOffset value from a local time with
// the offset of the local time zone
DateTime localTime = DateTime.SpecifyKind(sourceDate, DateTimeKind.Local);
targetTime = new DateTimeOffset(localTime,
TimeZoneInfo.Local.GetUtcOffset(localTime));
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM -07:00
// Because the Kind property is DateTimeKind.Local and the offset matches
// that of the local time zone, the call to the constructor succeeds.
// Instantiate a DateTimeOffset value from a local time with a zero offset.
try
{
targetTime = new DateTimeOffset(localTime, TimeSpan.Zero);
Console.WriteLine(targetTime);
}
catch (ArgumentException)
{
Console.WriteLine("Attempt to create DateTimeOffset value from {0} failed.",
localTime);
}
// Throws exception and displays the following to the console:
// Attempt to create DateTimeOffset value from 5/1/2008 8:30:00 AM failed.
// Instantiate a DateTimeOffset value with an arbitrary time zone.
string timeZoneName = "Central Standard Time";
TimeSpan offset = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName).
GetUtcOffset(sourceDate);
targetTime = new DateTimeOffset(sourceDate, offset);
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM -05:00
Dim sourceDate As Date = #5/1/2008 8:30 AM#
Dim targetTime As DateTimeOffset
' Instantiate a DateTimeOffset value from a UTC time with a zero offset.
Dim utcTime As Date = Date.SpecifyKind(sourceDate, DateTimeKind.Utc)
targetTime = New DateTimeOffset(utcTime, TimeSpan.Zero)
Console.WriteLine(targetTime)
' Displays 5/1/2008 8:30:00 AM +00:00
' Because the Kind property is DateTimeKind.Utc,
' the call to the constructor succeeds.
' Instantiate a DateTimeOffset value from a UTC time with a non-zero offset.
Try
targetTime = New DateTimeOffset(utcTime, New TimeSpan(-2, 0, 0))
Console.WriteLine(targetTime)
Catch e As ArgumentException
Console.WriteLine("Attempt to create DateTimeOffset value from {0} failed.", _
utcTime)
End Try
' Throws exception and displays the following to the console:
' Attempt to create DateTimeOffset value from 5/1/2008 8:30:00 AM failed.
' Instantiate a DateTimeOffset value from a local time with
' the offset of the local time zone.
Dim localTime As Date = Date.SpecifyKind(sourceDate, DateTimeKind.Local)
targetTime = New DateTimeOffset(localTime, _
TimeZoneInfo.Local.GetUtcOffset(localTime))
Console.WriteLine(targetTime)
' Because the Kind property is DateTimeKind.Local and the offset matches
' that of the local time zone, the call to the constructor succeeds.
' Instantiate a DateTimeOffset value from a local time with a zero offset.
Try
targetTime = New DateTimeOffset(localTime, TimeSpan.Zero)
Console.WriteLine(targetTime)
Catch e As ArgumentException
Console.WriteLine("Attempt to create DateTimeOffset value from {0} failed.", _
localTime)
End Try
' Throws exception and displays the following to the console:
' Attempt to create DateTimeOffset value from 5/1/2008 8:30:00 AM failed.
' Instantiate a DateTimeOffset value with an arbitrary time zone.
Dim timeZoneName As String = "Central Standard Time"
Dim offset As TimeSpan = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName). _
GetUtcOffset(sourceDate)
targetTime = New DateTimeOffset(sourceDate, offset)
Console.WriteLine(targetTime)
' Displays 5/1/2008 8:30:00 AM -05:00
Implicit type conversion
The DateTimeOffset type supports one implicit type conversion: from a DateTime value to a DateTimeOffset value. (An implicit type conversion is a conversion from one type to another that does not require an explicit cast (in C#) or conversion (in Visual Basic) and that does not lose information.) It makes code like the following possible.
DateTimeOffset targetTime;
// The Kind property of sourceDate is DateTimeKind.Unspecified
DateTime sourceDate = new DateTime(2008, 5, 1, 8, 30, 0);
targetTime = sourceDate;
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM -07:00
// define a UTC time (Kind property is DateTimeKind.Utc)
DateTime utcTime = DateTime.SpecifyKind(sourceDate, DateTimeKind.Utc);
targetTime = utcTime;
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM +00:00
// Define a local time (Kind property is DateTimeKind.Local)
DateTime localTime = DateTime.SpecifyKind(sourceDate, DateTimeKind.Local);
targetTime = localTime;
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM -07:00
Dim targetTime As DateTimeOffset
' The Kind property of sourceDate is DateTimeKind.Unspecified
Dim sourceDate As Date = #5/1/2008 8:30 AM#
targetTime = sourceDate
Console.WriteLine(targetTime)
' Displays 5/1/2008 8:30:00 AM -07:00
' define a UTC time (Kind property is DateTimeKind.Utc)
Dim utcTime As Date = Date.SpecifyKind(sourceDate, DateTimeKind.Utc)
targetTime = utcTime
Console.WriteLine(targetTime)
' Displays 5/1/2008 8:30:00 AM +00:00
' Define a local time (Kind property is DateTimeKind.Local)
Dim localTime As Date = Date.SpecifyKind(sourceDate, DateTimeKind.Local)
targetTime = localTime
Console.WriteLine(targetTime)
' Displays 5/1/2008 8:30:00 AM -07:00
The offset of the resulting DateTimeOffset value depends on the DateTime.Kind property value. If its value is DateTimeKind.Utc, the offset is set equal to TimeSpan.Zero. If its value is either DateTimeKind.Local or DateTimeKind.Unspecified, the offset is set equal to that of the local time zone.
Parsing the string representation of a date and time
The DateTimeOffset type supports four methods that allow you to convert the string representation of a date and time into a DateTimeOffset value:
Parse, which tries to convert the string representation of a date and time to a DateTimeOffset value and throws an exception if the conversion fails.
TryParse, which tries to convert the string representation of a date and time to a DateTimeOffset value and returns
false
if the conversion fails.ParseExact, which tries to convert the string representation of a date and time in a specified format to a DateTimeOffset value. The method throws an exception if the conversion fails.
TryParseExact, which tries to convert the string representation of a date and time in a specified format to a DateTimeOffset value. The method returns
false
if the conversion fails.
The following example illustrates calls to each of these four string conversion methods to instantiate a DateTimeOffset value.
string timeString;
DateTimeOffset targetTime;
timeString = "05/01/2008 8:30 AM +01:00";
try
{
targetTime = DateTimeOffset.Parse(timeString);
Console.WriteLine(targetTime);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse {0}.", timeString);
}
timeString = "05/01/2008 8:30 AM";
if (DateTimeOffset.TryParse(timeString, out targetTime))
Console.WriteLine(targetTime);
else
Console.WriteLine("Unable to parse {0}.", timeString);
timeString = "Thursday, 01 May 2008 08:30";
try
{
targetTime = DateTimeOffset.ParseExact(timeString, "f",
CultureInfo.InvariantCulture);
Console.WriteLine(targetTime);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse {0}.", timeString);
}
timeString = "Thursday, 01 May 2008 08:30 +02:00";
string formatString;
formatString = CultureInfo.InvariantCulture.DateTimeFormat.LongDatePattern +
" " +
CultureInfo.InvariantCulture.DateTimeFormat.ShortTimePattern +
" zzz";
if (DateTimeOffset.TryParseExact(timeString,
formatString,
CultureInfo.InvariantCulture,
DateTimeStyles.AllowLeadingWhite,
out targetTime))
Console.WriteLine(targetTime);
else
Console.WriteLine("Unable to parse {0}.", timeString);
// The example displays the following output to the console:
// 5/1/2008 8:30:00 AM +01:00
// 5/1/2008 8:30:00 AM -07:00
// 5/1/2008 8:30:00 AM -07:00
// 5/1/2008 8:30:00 AM +02:00
Dim timeString As String
Dim targetTime As DateTimeOffset
timeString = "05/01/2008 8:30 AM +01:00"
Try
targetTime = DateTimeOffset.Parse(timeString)
Console.WriteLine(targetTime)
Catch e As FormatException
Console.WriteLine("Unable to parse {0}.", timeString)
End Try
timeString = "05/01/2008 8:30 AM"
If DateTimeOffset.TryParse(timeString, targetTime) Then
Console.WriteLine(targetTime)
Else
Console.WriteLine("Unable to parse {0}.", timeString)
End If
timeString = "Thursday, 01 May 2008 08:30"
Try
targetTime = DateTimeOffset.ParseExact(timeString, "f", _
CultureInfo.InvariantCulture)
Console.WriteLine(targetTime)
Catch e As FormatException
Console.WriteLine("Unable to parse {0}.", timeString)
End Try
timeString = "Thursday, 01 May 2008 08:30 +02:00"
Dim formatString As String
formatString = CultureInfo.InvariantCulture.DateTimeFormat.LongDatePattern & _
" " & _
CultureInfo.InvariantCulture.DateTimeFormat.ShortTimePattern & _
" zzz"
If DateTimeOffset.TryParseExact(timeString, _
formatString, _
CultureInfo.InvariantCulture, _
DateTimeStyles.AllowLeadingWhite, _
targetTime) Then
Console.WriteLine(targetTime)
Else
Console.WriteLine("Unable to parse {0}.", timeString)
End If
' The example displays the following output to the console:
' 5/1/2008 8:30:00 AM +01:00
' 5/1/2008 8:30:00 AM -07:00
' 5/1/2008 8:30:00 AM -07:00
' 5/1/2008 8:30:00 AM +02:00