C # convert string to date

I have a line like this "24:00:00" and I would like to convert it in time. I tried converting DateTime.Parse as well, but it seems like it needs a date too. Is there a way to just get the time, or do I need to set a date too?

+7
source share
6 answers

If you are only interested in the time component, consider using a TimeSpan instead of a full DateTime .

 var time = TimeSpan.Parse("23:59:59"); 
+15
source

I'm not sure that โ€œ24:00:00โ€ will be the right time. Any, like, you do not need to indicate a date, you can do ...

 DateTime time = DateTime.ParseExact("23:59:59", "HH:mm:ss", null); 

If your time is actually the time of day, I would suggest sticking with DateTime. If you are actually using some amount of time (that is, it may be more than 23:59:59), you can use TimeSpan ...

 TimeSpan time = TimeSpan.ParseExact("23:59:59", "HH:mm:ss", null); 

do not forget that both have a version of TryParseExact if you are not sure that the input you entered will be valid.

+3
source

You can use DateTimeFormatInfo to format DateTime.

 string strDate = "23:10:00"; DateTimeFormatInfo dtfi = new DateTimeFormatInfo(); dtfi.ShortTimePattern = "hh:mm:ss"; dtfi.TimeSeparator = ":"; DateTime objDate = Convert.ToDateTime(strDate, dtfi); Console.WriteLine(objDate.TimeOfDay.ToString()); 
+2
source

I think you need TimeSpan.Parse instead?

+1
source
0
source

What about

 var time = new DateTime.Today; var str = "24:00:00"; var split = str.split(":"); time.AddHours(Convert.ToInt32(split[0])); time.AddMinutes(Convert.ToInt32(split[1])); time.AddSeconds(Convert.ToInt32(split[2])); 

Hope this helps.

0
source

All Articles