CSharp - Date Time DateTimeOffset Creation

Introduction

DateTimeOffset accepts a UTC offset as a TimeSpan in its constructors.

public DateTimeOffset (int year, int month, int day,
                       int hour, int minute, int second,
                       TimeSpan offset);

public DateTimeOffset (int year, int month, int day,
                       int hour, int minute, int second, int millisecond,
                       TimeSpan offset);

TimeSpan passed in must be a whole number of minutes, or an exception is thrown.

You can also use Calendar object to create DateTimeOffset along with a long ticks value.

You can construct a DateTimeOffset from an existing DateTime:

public DateTimeOffset (DateTime dateTime);
public DateTimeOffset (DateTime dateTime, TimeSpan offset);

or with an implicit cast:

DateTimeOffset dt = new DateTime (2000, 2, 3);

If you don't specify an offset, DateTimeOffset is inferred from the DateTime value using these rules:

  • If the DateTime has a DateTimeKind of Utc, the offset is zero.
  • If the DateTime has a DateTimeKind of Local or Unspecified, the offset is taken from the current local time zone.

To get DateTime from DateTimeOffset:

  • UtcDateTime property returns a DateTime in UTC time.
  • LocalDateTime property returns a DateTime in the current local time zone.
  • DateTime property returns a DateTime in whatever zone it was specified, with a Kind of Unspecified (UTC time plus the offset).

Related Topics