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 is obviously of DateTime
datatype.
I know I could break this string on :
and use first part as hours and then convert that to double and then use AddHours, and I should repeat that for minutes also but I'm wonder is there convenient way to do this?
You can use TimeSpan.ParseExact
:
myobj.StartTime = myobj.StartTime.Add(TimeSpan.ParseExact(date, "hh\\:mm", CultureInfo.InvariantCulture));
In hh\\:mm
hh
are hours (you cannot use HH
here, not supported by this concrete method), mm
are minutes, and \\:
is escaped :
character. One slash is to escape slash itself in C# literal string (otherwise you can do this: @"hh\:mm"
), and you need to escape :
with slash in format string, because otherwise TimeSpan.ParseExact
will treat it as custom format specifier (like h
), but there is no such format specifier and it will throw invalid format exception.
Note that if you also allow single-digit hours and minutes (like this: "1:2" or "1:25") - then you have to use another format:
TimeSpan.ParseExact(date, @"h\:m", CultureInfo.InvariantCulture);
This format will handle both single-digit and two-digit hours and minutes.
Also note that if you have more than 24 hours in your string (like "25:11") - this method will not work and you will have to fallback to split (as far as I know).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With