DateTimeOffset Structure (System)

Switch View :
ScriptFree
.NET Framework Class Library
DateTimeOffset Structure

Represents a point in time, typically expressed as a date and time of day, relative to Coordinated Universal Time (UTC).

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
Syntax

Visual Basic
<SerializableAttribute> _
Public Structure DateTimeOffset _
	Implements IComparable, IFormattable, ISerializable, IDeserializationCallback,  _
	IComparable(Of DateTimeOffset), IEquatable(Of DateTimeOffset)
C#
[SerializableAttribute]
public struct DateTimeOffset : IComparable, 
	IFormattable, ISerializable, IDeserializationCallback, IComparable<DateTimeOffset>, 
	IEquatable<DateTimeOffset>
Visual C++
[SerializableAttribute]
public value class DateTimeOffset : IComparable, 
	IFormattable, ISerializable, IDeserializationCallback, IComparable<DateTimeOffset>, 
	IEquatable<DateTimeOffset>
F#
[<Sealed>]
[<SerializableAttribute>]
type DateTimeOffset =  
    struct
        interface IComparable
        interface IFormattable
        interface ISerializable
        interface IDeserializationCallback
        interface IComparable<DateTimeOffset>
        interface IEquatable<DateTimeOffset>
    end

The DateTimeOffset type exposes the following members.

Constructors

  Name Description
Public method Supported by Portable Class Library DateTimeOffset(DateTime) Initializes a new instance of the DateTimeOffset structure using the specified DateTime value.
Public method Supported by Portable Class Library DateTimeOffset(DateTime, TimeSpan) Initializes a new instance of the DateTimeOffset structure using the specified DateTime value and offset.
Public method Supported by Portable Class Library DateTimeOffset(Int64, TimeSpan) Initializes a new instance of the DateTimeOffset structure using the specified number of ticks and offset.
Public method Supported by Portable Class Library DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, TimeSpan) Initializes a new instance of the DateTimeOffset structure using the specified year, month, day, hour, minute, second, and offset.
Public method Supported by Portable Class Library DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, TimeSpan) Initializes a new instance of the DateTimeOffset structure using the specified year, month, day, hour, minute, second, millisecond, and offset.
Public method Supported by Portable Class Library DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, TimeSpan) Initializes a new instance of the DateTimeOffset structure using the specified year, month, day, hour, minute, second, millisecond, and offset of a specified calendar.
Top
Properties

  Name Description
Public property Supported by Portable Class Library Date Gets a DateTime value that represents the date component of the current DateTimeOffset object.
Public property Supported by Portable Class Library DateTime Gets a DateTime value that represents the date and time of the current DateTimeOffset object.
Public property Supported by Portable Class Library Day Gets the day of the month represented by the current DateTimeOffset object.
Public property Supported by Portable Class Library DayOfWeek Gets the day of the week represented by the current DateTimeOffset object.
Public property Supported by Portable Class Library DayOfYear Gets the day of the year represented by the current DateTimeOffset object.
Public property Supported by Portable Class Library Hour Gets the hour component of the time represented by the current DateTimeOffset object.
Public property Supported by Portable Class Library LocalDateTime Gets a DateTime value that represents the local date and time of the current DateTimeOffset object.
Public property Supported by Portable Class Library Millisecond Gets the millisecond component of the time represented by the current DateTimeOffset object.
Public property Supported by Portable Class Library Minute Gets the minute component of the time represented by the current DateTimeOffset object.
Public property Supported by Portable Class Library Month Gets the month component of the date represented by the current DateTimeOffset object.
Public property Static member Supported by Portable Class Library Now Gets a DateTimeOffset object that is set to the current date and time on the current computer, with the offset set to the local time's offset from Coordinated Universal Time (UTC).
Public property Supported by Portable Class Library Offset Gets the time's offset from Coordinated Universal Time (UTC).
Public property Supported by Portable Class Library Second Gets the second component of the clock time represented by the current DateTimeOffset object.
Public property Supported by Portable Class Library Ticks Gets the number of ticks that represents the date and time of the current DateTimeOffset object in clock time.
Public property Supported by Portable Class Library TimeOfDay Gets the time of day for the current DateTimeOffset object.
Public property Supported by Portable Class Library UtcDateTime Gets a DateTime value that represents the Coordinated Universal Time (UTC) date and time of the current DateTimeOffset object.
Public property Static member Supported by Portable Class Library UtcNow Gets a DateTimeOffset object whose date and time are set to the current Coordinated Universal Time (UTC) date and time and whose offset is TimeSpan.Zero.
Public property Supported by Portable Class Library UtcTicks Gets the number of ticks that represents the date and time of the current DateTimeOffset object in Coordinated Universal Time (UTC).
Public property Supported by Portable Class Library Year Gets the year component of the date represented by the current DateTimeOffset object.
Top
Methods

  Name Description
Public method Supported by Portable Class Library Add Adds a specified time interval to a DateTimeOffset object.
Public method Supported by Portable Class Library AddDays Adds a specified number of whole and fractional days to the current DateTimeOffset object.
Public method Supported by Portable Class Library AddHours Adds a specified number of whole and fractional hours to the current DateTimeOffset object.
Public method Supported by Portable Class Library AddMilliseconds Adds a specified number of milliseconds to the current DateTimeOffset object.
Public method Supported by Portable Class Library AddMinutes Adds a specified number of whole and fractional minutes to the current DateTimeOffset object.
Public method Supported by Portable Class Library AddMonths Adds a specified number of months to the current DateTimeOffset object.
Public method Supported by Portable Class Library AddSeconds Adds a specified number of whole and fractional seconds to the current DateTimeOffset object.
Public method Supported by Portable Class Library AddTicks Adds a specified number of ticks to the current DateTimeOffset object.
Public method Supported by Portable Class Library AddYears Adds a specified number of years to the DateTimeOffset object.
Public method Static member Supported by Portable Class Library Compare Compares two DateTimeOffset objects and indicates whether the first is earlier than the second, equal to the second, or later than the second.
Public method Supported by Portable Class Library CompareTo Compares the current DateTimeOffset object to a specified DateTimeOffset object and indicates whether the current object is earlier than, the same as, or later than the second DateTimeOffset object.
Public method Supported by Portable Class Library Equals(DateTimeOffset) Determines whether the current DateTimeOffset object represents the same point in time as a specified DateTimeOffset object.
Public method Supported by Portable Class Library Equals(Object) Determines whether a DateTimeOffset object represents the same point in time as a specified object. (Overrides ValueType.Equals(Object).)
Public method Static member Supported by Portable Class Library Equals(DateTimeOffset, DateTimeOffset) Determines whether two specified DateTimeOffset objects represent the same point in time.
Public method Supported by Portable Class Library EqualsExact Determines whether the current DateTimeOffset object represents the same time and has the same offset as a specified DateTimeOffset object.
Protected method Supported by Portable Class Library Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Static member FromFileTime Converts the specified Windows file time to an equivalent local time.
Public method Supported by Portable Class Library GetHashCode Returns the hash code for the current DateTimeOffset object. (Overrides ValueType.GetHashCode().)
Public method Supported by Portable Class Library GetType Gets the Type of the current instance. (Inherited from Object.)
Protected method Supported by Portable Class Library MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method Static member Parse(String) Converts the specified string representation of a date, time, and offset to its DateTimeOffset equivalent.
Public method Static member Supported by Portable Class Library Parse(String, IFormatProvider) Converts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified culture-specific format information.
Public method Static member Supported by Portable Class Library Parse(String, IFormatProvider, DateTimeStyles) Converts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified culture-specific format information and formatting style.
Public method Static member Supported by Portable Class Library ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
Public method Static member Supported by Portable Class Library ParseExact(String, String, IFormatProvider, DateTimeStyles) Converts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly.
Public method Static member Supported by Portable Class Library ParseExact(String, String[], IFormatProvider, DateTimeStyles) Converts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified formats, culture-specific format information, and style. The format of the string representation must match one of the specified formats exactly.
Public method Supported by Portable Class Library Subtract(DateTimeOffset) Subtracts a DateTimeOffset value that represents a specific date and time from the current DateTimeOffset object.
Public method Supported by Portable Class Library Subtract(TimeSpan) Subtracts a specified time interval from the current DateTimeOffset object.
Public method ToFileTime Converts the value of the current DateTimeOffset object to a Windows file time.
Public method Supported by Portable Class Library ToLocalTime Converts the current DateTimeOffset object to a DateTimeOffset object that represents the local time.
Public method Supported by Portable Class Library ToOffset Converts the value of the current DateTimeOffset object to the date and time specified by an offset value.
Public method Supported by Portable Class Library ToString() Converts the value of the current DateTimeOffset object to its equivalent string representation. (Overrides ValueType.ToString().)
Public method Supported by Portable Class Library ToString(IFormatProvider) Converts the value of the current DateTimeOffset object to its equivalent string representation using the specified culture-specific formatting information.
Public method ToString(String) Converts the value of the current DateTimeOffset object to its equivalent string representation using the specified format.
Public method Supported by Portable Class Library ToString(String, IFormatProvider) Converts the value of the current DateTimeOffset object to its equivalent string representation using the specified format and culture-specific format information.
Public method Supported by Portable Class Library ToUniversalTime Converts the current DateTimeOffset object to a DateTimeOffset value that represents the Coordinated Universal Time (UTC).
Public method Static member TryParse(String, DateTimeOffset) Tries to converts a specified string representation of a date and time to its DateTimeOffset equivalent, and returns a value that indicates whether the conversion succeeded.
Public method Static member Supported by Portable Class Library TryParse(String, IFormatProvider, DateTimeStyles, DateTimeOffset) Tries to convert a specified string representation of a date and time to its DateTimeOffset equivalent, and returns a value that indicates whether the conversion succeeded.
Public method Static member Supported by Portable Class Library TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTimeOffset) Converts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly.
Public method Static member Supported by Portable Class Library TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTimeOffset) Converts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified array of formats, culture-specific format information, and style. The format of the string representation must match one of the specified formats exactly.
Top
Operators

  Name Description
Public operator Static member Supported by Portable Class Library Addition Adds a specified time interval to a DateTimeOffset object that has a specified date and time, and yields a DateTimeOffset object that has new a date and time.
Public operator Static member Supported by Portable Class Library Equality Determines whether two specified DateTimeOffset objects represent the same point in time.
Public operator Static member Supported by Portable Class Library GreaterThan Determines whether one specified DateTimeOffset object is greater than (or later than) a second specified DateTimeOffset object.
Public operator Static member Supported by Portable Class Library GreaterThanOrEqual Determines whether one specified DateTimeOffset object is greater than or equal to a second specified DateTimeOffset object.
Public operator Static member Supported by Portable Class Library Implicit(DateTime to DateTimeOffset) Defines an implicit conversion of a DateTime object to a DateTimeOffset object.
Public operator Static member Supported by Portable Class Library Inequality Determines whether two specified DateTimeOffset objects refer to different points in time.
Public operator Static member Supported by Portable Class Library LessThan Determines whether one specified DateTimeOffset object is less than a second specified DateTimeOffset object.
Public operator Static member Supported by Portable Class Library LessThanOrEqual Determines whether one specified DateTimeOffset object is less than a second specified DateTimeOffset object.
Public operator Static member Supported by Portable Class Library Subtraction(DateTimeOffset, DateTimeOffset) Subtracts one DateTimeOffset object from another and yields a time interval.
Public operator Static member Supported by Portable Class Library Subtraction(DateTimeOffset, TimeSpan) Subtracts a specified time interval from a specified date and time, and yields a new date and time.
Top
Fields

  Name Description
Public field Static member Supported by Portable Class Library MaxValue Represents the greatest possible value of DateTimeOffset. This field is read-only.
Public field Static member Supported by Portable Class Library MinValue Represents the earliest possible DateTimeOffset value. This field is read-only.
Top
Explicit Interface Implementations

  Name Description
Explicit interface implemetation Private method IComparable.CompareTo Infrastructure. Compares the value of the current DateTimeOffset object with another object of the same type.
Explicit interface implemetation Private method IDeserializationCallback.OnDeserialization Infrastructure. Runs when the deserialization of an object has been completed.
Explicit interface implemetation Private method ISerializable.GetObjectData Infrastructure. Populates a SerializationInfo object with the data required to serialize the current DateTimeOffset object.
Top
Remarks

The DateTimeOffset structure includes a DateTime value, together with an Offset property that defines the difference between the current DateTimeOffset instance's date and time and Coordinated Universal Time (UTC). Because it exactly defines a date and time relative to UTC, the DateTimeOffset structure does not include a Kind member, as the DateTime structure does. It represents dates and times with values whose UTC ranges from 12:00:00 midnight, January 1, 0001 Anno Domini (Common Era), to 11:59:59 P.M., December 31, 9999 A.D. (C.E.).

The time component of a DateTimeOffset value is measured in 100-nanosecond units called ticks, and a particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in the GregorianCalendar calendar. A DateTimeOffset value is always expressed in the context of an explicit or default calendar. Ticks that are attributable to leap seconds are not included in the total number of ticks.

Note Note

   If you are working with a ticks value that you want to convert to some other time interval, such as minutes or seconds, you should use the TimeSpan.TicksPerDay, TimeSpan.TicksPerHour, TimeSpan.TicksPerMinute, TimeSpan.TicksPerSecond, or TimeSpan.TicksPerMillisecond constant to perform the conversion. For example, to add the number of seconds represented by a specified number of ticks to the Second component of a DateTimeOffset value, you can use the expression dateValue.Second + nTicks/Timespan.TicksPerSecond.

Although a DateTimeOffset value includes an offset, it is not a fully time zone-aware data structure. While an offset from UTC is one characteristic of a time zone, it does not unambiguously identify a time zone. Not only do multiple time zones share the same offset from UTC, but the offset of a single time zone changes if it observes daylight saving time. This means that, as soon as a DateTimeOffset value is disassociated from its time zone, it can no longer be unambiguously linked back to its original time zone.

Because DateTimeOffset is a structure, a DateTimeOffset object that has been declared but not otherwise initialized contains the default values for each of its member fields. This means that its DateTime property is set to DateTimeOffset.MinValue and its Offset property is set to TimeSpan.Zero.

You can create a new DateTimeOffset value by calling any of the overloads of its constructor, which are similar to the overloaded constructors for the DateTime structure. You can also create a new DateTimeOffset value by assigning it a DateTime value. This is an implicit conversion; it does not require a casting operator (in C#) or call to a conversion method (in Visual Basic). You can also initialize a DateTimeOffset value from the string representation of a date and time by calling a number of static string parsing methods, which include Parse, ParseExact, TryParse, and TryParseExact.

The members of the DateTimeOffset structure provide functionality in the following areas:

  • Date and time arithmetic.

    You can add or subtract either dates or time intervals from a particular DateTimeOffset value. Arithmetic operations with DateTimeOffset values, unlike those with DateTime values, adjust for differences in time offsets when returning a result. For example, the following code uses DateTime variables to subtract the current local time from the current UTC time. The code then uses DateTimeOffset variables to perform the same operation. The subtraction with DateTime values returns the local time zone's difference from UTC, while the subtraction with DateTimeOffset values returns TimeSpan.Zero.

    Visual Basic
    
    Module DateArithmetic
       Public Sub Main()
          Dim date1, date2 As Date
          Dim dateOffset1, dateOffset2 As DateTimeOffset
          Dim difference As TimeSpan
    
          ' Find difference between Date.Now and Date.UtcNow
          date1 = Date.Now
          date2 = Date.UtcNow
          difference = date1 - date2
          Console.WriteLine("{0} - {1} = {2}", date1, date2, difference)
    
          ' Find difference between Now and UtcNow using DateTimeOffset
          dateOffset1 = date.Now
          dateOffset2 = date.UtcNow
          difference = dateOffset1 - dateOffset2
          Console.WriteLine("{0} - {1} = {2}", _
                            dateOffset1, dateOffset2, difference)
          ' If run in the Pacific Standard time zone on 4/2/2007, the example
          ' displays the following output to the console:
          '    4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00
          '    4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM +00:00 = 00:00:00                        
       End Sub
    End Module
    
    
    
    C#
    
    using System;
    
    public class DateArithmetic
    {
       public static void Main()
       {
          DateTime date1, date2;
          DateTimeOffset dateOffset1, dateOffset2;
          TimeSpan difference;
    
          // Find difference between Date.Now and Date.UtcNow
          date1 = DateTime.Now;
          date2 = DateTime.UtcNow;
          difference = date1 - date2;
          Console.WriteLine("{0} - {1} = {2}", date1, date2, difference);
    
          // Find difference between Now and UtcNow using DateTimeOffset
          dateOffset1 = DateTimeOffset.Now;
          dateOffset2 = DateTimeOffset.UtcNow;
          difference = dateOffset1 - dateOffset2;
          Console.WriteLine("{0} - {1} = {2}", 
                            dateOffset1, dateOffset2, difference);
          // If run in the Pacific Standard time zone on 4/2/2007, the example
          // displays the following output to the console:
          //    4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00
          //    4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM +00:00 = 00:00:00                        
       }
    }
    
    
    
  • Type conversion operations.

    You can convert DateTimeOffset values to DateTime values and vice versa.

  • Time manipulation and extraction operations.

    You can extract either the date or the time of a DateTimeOffset value. You can also retrieve the value of a particular DateTimeOffset component, such as its year or its month.

  • Date and time conversion.

    You can convert any DateTimeOffset value to another DateTimeOffset value that represents the same point in time in another time zone. However, a time zone's adjustment rules are applied only in the case of the ToLocalTime method, which converts a DateTimeOffset value to the date and time in the local system zone.

  • Date and time comparison.

    You can determine whether any particular DateTimeOffset value is earlier than, the same as, or later than another DateTimeOffset value. Before the comparison is performed, all values are converted to UTC.

Version Information

.NET Framework

Supported in: 4, 3.5 SP1, 3.0 SP1, 2.0 SP1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library
Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
See Also

Reference

Other Resources

Community Content

mattj1856
Not True...
"If a DateTimeOffset in the UK was cached or persisted for a whole weekend, the clocks may have gone back/forward for British Summer Time and the offset would then be wrong on the Monday."

You are missing the point.  The offset is relative to the date represented.  Using your example of GMT/BST, you can take the time at noon before the clock change and it would be "2011-03-26 12:00+0000".  When you take it again at noon after the change it would be "2011-03-27 12:00+0100".   The original value is still correct unto itself.  In other words, you would never have "2011-03-26 12:00+0100".

I read it as "on <date> at <time>, the UTC offset was <offset>."  It then seems that really the DateTimeOffset is just for the convience of showing dates at the local time when you aren't storing the time zone, and still being able to compare in a time-zone independant manner.

So in other words:
- If you will always know the time zone that the date is taken in, you can safely use just a regular DateTime with the UTC time.
- If you are not going to keep track of that time zone, then you should use DateTimeOffset so that you can view the time as it was originally created, but still being able to sort it universally.


R Petrusha - MSFT
DateTimeOffset broken too?

I don't understand why DateTime/DateTimeOffset was not designed to simply hold the UTC time, and nothing more. The local time can easily be calculated when you need it. This is like Windows always did it: time stamps in NTFS is UTC, and there never was any problems until .NET came along?

Why Not Just UTC Time?

While it is true that UTC time ensures that date and time data can be accurately preserved across machine boundaries, it is also true that a data type that can represent UTC time only is unable to reflect dates and times in specific time zones. The DateTimeOffset structure aims to do precisely this: to reflect a single instant in time as it is represented in any time zone. The DateTimeOffset structure in turn facilitates a new class of applications that use historic time zone data and that, when used with the conversion methods in the TimeZoneInfo class, make it easy to convert the time from one time zone to another.

--Ron Petrusha
Base Class Library Developer Content
Microsoft Corporation


LukePuplett
DateTimeOffset is not a panacea for global web apps

"the offset of a single time zone changes if it observes daylight saving time. This means that, as soon as a DateTimeOffset value is disassociated from its time zone, it can no longer be unambiguously linked back to its original time zone."

Empirically, DateTimeOffset is suitable for short term in-memory calculations, conversions and comparisons usually on the server side, once the offset has been established. A TimeZoneInfo is still required because it is aware of any changes to the offset throughout the year.

If a DateTimeOffset in the UK was cached or persisted for a whole weekend, the clocks may have gone back/forward for British Summer Time and the offset would then be wrong on the Monday.