4

I would like to set default value to DateTimeOffset - it should not be DateTime.Now but rather DateTime.MinValue or default(DateTime)

Any thoughts how can I do it? This code:

DateTimeOffset d = new DateTimeOffset(DateTime.MinValue)

throws an exception

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
YAKOVM
  • 9,805
  • 31
  • 116
  • 217
  • What do you mean by "set default value to DateTimeOffset"? And what exception are you seeing? – Jon Skeet Feb 25 '15 at 13:16
  • 3
    So doesn't `default(DateTimeOffset)` do what you want, then? – Jeroen Mostert Feb 25 '15 at 13:17
  • "it should not be DateTime.Now". I don't know if the default value for `DateTimeOffset`´s Date property used to be `DateTime.Now` years ago, but today the default value is `DateTimeOffset.MinValue` – thesystem Nov 08 '21 at 13:54

1 Answers1

15

The reason this code throws an exception for you is that you're presumably in a time zone which is ahead of UTC - so when DateTime.MinValue (which has a Kind of Unspecified) is converted to UTC, it's becoming invalid. The conversion is specified in the documentation:

If the value of DateTime.Kind is DateTimeKind.Local or DateTimeKind.Unspecified, the DateTime property of the new instance is set equal to dateTime, and the Offset property is set equal to the offset of the local system's current time zone.

You could just specify the offset explicitly though:

DateTimeOffset d = new DateTimeOffset(DateTime.MinValue, TimeSpan.Zero);

That won't result in any conversion... but I believe it's exactly equivalen to default(DateTimeOffset). (It's more explicit, mind you - often a good thing.)

You might also want to consider using DateTimeOffset? and specifying null for the absence of a "real" value, instead of just using a dummy value.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194