-1

I have following code:

public sealed class MyClass
{
    [XmlElement("Remind")]
    public string lastUpdatedTimeForXml2
    {
         get { return Remind.ToString("yyyy-MM-ddTHH:mm:ss"); }
         set { Remind = DateTimeOffset.Parse(value); }
    }
    [XmlIgnore]
    public DateTimeOffset Remind { get; set; }
}

And my problem is when the Remind value not exist in file it's replacing it by 0001-01-01T00:00:00 and crashing at line: "set { Remind = DateTimeOffset.Parse(value); }"

EDIT.

Ok, I solved it doing something like this:

    [XmlElement("Remind")]
    public string lastUpdatedTimeForXml2
    {
        get { return Remind.ToString("yyyy-MM-ddTHH:mm:ss"); }
        set
        {
            if (value == "0001-01-01T00:00:00")
                Remind = DateTimeOffset.MinValue;
            else
                Remind = DateTimeOffset.Parse(value);
        }
    }
    [XmlIgnore]

Now isn't crashing, but i don't know why. This is the best solution?

GoOx
  • 73
  • 1
  • 1
  • 9
  • You are on the Eastern hemisphere, right? You get the exception message _The UTC representation of the date falls outside the year range 1-9999._, don't you? What time zone are you expecting. (You can use `TryParse` if you want.) – Jeppe Stig Nielsen Aug 15 '16 at 13:16

1 Answers1

2

Added preface: When you parse a string like "0001-01-01T00:00:00" which has no time zone clues, and when your machine's local time zone is on the Eastern Hemisphere (ahead of UTC), the underlying UTC value will be somewhere in the year prior to year 0001, which is not supported. You will get an exception message:

The UTC representation of the date falls outside the year range 1-9999.


It is hard to answer if you do not specify what you want. One possibility is:

set { Remind = DateTimeOffset.Parse(value, null, DateTimeStyles.AssumeUniversal)); }

This will change the time zone assumed when the string value gives no time zone information.

Another option is:

set
{
  DateTimeOffset remind;
  DateTimeOffset.TryParse(value, out remind);
  Remind = remind;
}

It will "fall back" to default(DateTimeOffset) when the parse fails.

Do you desire some kind of "round-trip", such that the string produced by the get accessor can go back into the set accessor? In the case maybe you should change the format "yyyy-MM-ddTHH:mm:ss" in the getter to include time zone information?


Addition after your comment: I think you should use Remind.ToString("o") if you do not want to lose information. The standard format string "o" is meant for round-tripping (not losing information).

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181