How to convert HH: MM: SS string to datetime?

I have an input line HH: MM: SS, e.g. 15:43:13,

now i want to convert it to datetime but save only hour / time without date etc.

Is it possible?

eg

string userInput = 15:43:13; DateTime userInputTime = Convert.ToDateTime(userInput); 

will give me the full date including year etc. is there any way to convert it to HH: MM: SS without substring / substring?

thanks

+4
source share
3 answers

As others have said, this is a TimeSpan .

You can get datetime by doing this

 string userInput = "15:43:13"; var time = TimeSpan.Parse(userInput); var dateTime = DateTime.Today.Add(time); 
+11
source

To just get the time span, you can use:

 TimeSpan.Parse("15:43:13") 

But you have to ask yourself why you want to do this, as there are some pretty significant mistakes. For example, which 2:33 AM do you want when it rises, November 3, 2013, and daylight saving time ends? There are two of them.

+2
source

If you do not need additional data (year, etc.), use TimeSpan You can convert from user input to TimeSpan using Timespan.Parse

for example: TimeSpan ts = TimeSpan.Parse("6:12"); //06:12:00 TimeSpan ts = TimeSpan.Parse("6:12"); //06:12:00

More details here: http://msdn.microsoft.com/en-us/library/se73z7b9.aspx

0
source

Source: https://habr.com/ru/post/1480512/


All Articles