Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime un-representable error in C#

Tags:

c#

datetime

I have to add 15 minutes to the current time and set it to a DateTime object in C#. If my current time is say 11:50 PM, and 15 minutes is added, the hour part becomes 24 and is causing the following error: "Hour, Minute, and Second parameters describe an un-representable DateTime."

public static DateTime NewTime(this DateTime dateTime)
    {
        int hour = dateTime.Hour;
        int minute = dateTime.Minute;
        if (minute > 0)
        {
            minute = dateTime.Minute + (15);
            if (minute >= 60)
            {
                hour = hour + 1;
                minute = 0;
            }
        }
        return new DateTime(dateTime.Year, dateTime.Month,
             dateTime.Day, hour, minute, 0);
    }

Thanks

like image 408
Massey Avatar asked Jun 01 '26 22:06

Massey


2 Answers

Your logic does not make sense, you are only adding minutes if the minutes are greater than 0 so what happens if they are 0?

To add time use the methods built into the type definition, no need to reinvent the wheel. Example:

public static DateTime Add15Minutes(this DateTime dateTime)
{
    return dateTime.AddMinutes(15);
}
like image 176
Igor Avatar answered Jun 04 '26 23:06

Igor


I think you are overthinking this maybe? DateTime already provides many support methods and this will probably do what you need without the need to create an extension method:

var myValue = new DateTime(2017,3,14,23,50,0);
var result = myValue.AddMinutes(15);
like image 35
alfgar Avatar answered Jun 05 '26 01:06

alfgar