Dan272
Dan272

Reputation: 213

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

I am having an input string of HH:MM:SS for example 15:43:13.

Now, I want to convert it to datetime but keep just the hour/time without the date etc.

Is it possible?

For example:

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

Will it give me the full date including the year etc. ? Is there any way to convert it to just HH:MM:SS without trimming/substring?

Upvotes: 7

Views: 27146

Answers (3)

alc
alc

Reputation: 1557

To just get a time span, you can use:

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

But you should ask yourself why you want to do this as there are some fairly significant gotchas. For example, which 2:33 AM do you want when it's Sunday, November 3, 2013, and daylight savings time is ending? There are two of them.

Upvotes: 2

m4ttsson
m4ttsson

Reputation: 203

If you don't need the extra data (year etc.) use TimeSpan You can convert from the user input to a TimeSpan using Timespan.Parse

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

Read more here: http://msdn.microsoft.com/en-us/library/se73z7b9.aspx

Upvotes: 0

jgauffin
jgauffin

Reputation: 101140

As others have said, it's a TimeSpan.

You can get a datetime by doing this

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

Upvotes: 18

Related Questions