Search code examples
c#datetimetimesubtraction

DateTime error Subtracting from 0 hour


Using C# DateTime, I'd like to subtract a time past 0 (or midnight). However, I get an error when doing so. I'm trying to create a timeline where you can zoom in and out and scroll through the times. I get the following error: "The added or subtracted value results in an un-representable DateTime."

I guess DateTime doesn't know how to wrap back around from 0 to 23? How do I get around this?


Solution

  • If you subtract a TimeSpan from a DateTime, it will "wrap around" past midnight:

    > var d1 = DateTime.Parse("4/11/2012 12:30:00 AM");
    > var d2 = d1.Subtract(new TimeSpan(1, 15, 0));
    > 
    > d2
    [4/10/2012 11:15:00 PM]