Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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 give me the full date including the year etc, is there any way to convert it to just HH:MM:SS without triming/substring?

thanks

like image 839
Dan272 Avatar asked May 13 '13 15:05

Dan272


People also ask

How do you convert HH MM to timestamp?

Below is my coding: Object d = getMappedObjectValue(reportBeamDataMap, ReportBeamConstant. DAT_STOPDATE); Date stopDate1 = (Date)d; SimpleDateFormat printFormat = new SimpleDateFormat("hh:mm"); String timeString = printFormat. format(stopDate1);

How to convert date from string in c#?

Use the ToString() method to convert a date object to different formats as per your need. Use ToShortDateString() or ToShortTimeString() to get short date and time string. Use ToLongDateString() or ToLongTimeString() to get the date and time in long format.


2 Answers

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);
like image 161
jgauffin Avatar answered Oct 19 '22 21:10

jgauffin


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.

like image 35
Andrew Coonce Avatar answered Oct 19 '22 21:10

Andrew Coonce