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
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);
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.
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);
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.
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