Add hours and minutes from a string to a date and time

string date = "17:25"; if(date.Lenght == 5){ myobj.StartTime = DateTime.ParseExact(date, "HH:mm", CultureInfo.InvariantCulture); // add only hh and minutes and preserve day and year } else if(date.Lenght > 5){ myobj.StartTime = DateTime.ParseExact(date, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture); } 

myobj.StartTime obviously has a DateTime data type.

I know that I can break this line into : and use the first part as a clock, and then convert it to double, and then use AddHours, and I have to repeat this in a few minutes, but I wonder if there is a convenient way to do this?

+7
c # datetime
source share
1 answer

You can use TimeSpan.ParseExact :

 myobj.StartTime = myobj.StartTime.Add(TimeSpan.ParseExact(date, "hh\\:mm", CultureInfo.InvariantCulture)); 

There is a clock in hh\\:mm hh (you cannot use hh here, not supported by this particular method), mm is minutes, and \\: is an escaped character : One slash is to break out of a slash in a C # literal string (otherwise you can do this: @"hh\:mm" ) and you need to avoid : using a slash in the format, because otherwise TimeSpan.ParseExact will consider it as a specifier of a special format (for example, h ), but there is no such format specifier, and it will cause an invalid format exception.

Please note that if you also allow unambiguous hours and minutes (for example: "1: 2" or "1:25"), then you need to use a different format:

 TimeSpan.ParseExact(date, @"h\:m", CultureInfo.InvariantCulture); 

This format will handle both single-digit and double-digit hours and minutes.

Also note that if you have more than 24 hours in your line (for example, "25:11"), this method will not work, and you will have to refuse separation (as far as I know).

+11
source share

All Articles