I have a C# Visual Studio web application that uses Telerik RadTimePickers to collect the start time and end times, formatted as 24 hour time. These two elements get stored in the database as a string formatted as 09:00:00-09:30:00.
Now when the application retrieves the data from the database I need to convert that string into 2 separate times, in the 24 hour format, so I can use those values as the Selected Time for the RadTimePickers.
I use the code below to extract the two dates from the string;
if (Results.TimeOfDay != "-" || Results.TimeOfDay != null)
{
string[] times = Results.TimeOfDay.Split('-');
string time1 = times[0];
RadTimePicker1.SelectedTime = ParseTime(time1);
string time2 = times[1];
RadTimePicker2.SelectedTime = ParseTime(time2);
}
The Code for ParseTime looks like this:
static public TimeSpan ParseTime(string input)
{
TimeSpan output;
var ok = TimeSpan.TryParseExact(input, @"hh:mm:tt", CultureInfo.InvariantCulture,out output);
return output;
}
But it is not working, the var ok value returns false and the output value is 1/1/0001 12:00:00 AM.
New to C# and cannot figure out how to fix this problem. Can someone help please
Based on comments I changed the code to parse to this
static public TimeSpan ParseTime(string input)
{
TimeSpan output;
var ok = TimeSpan.TryParseExact(input, @"hh:mm:tt", CultureInfo.InvariantCulture,out output);
return output;
}
question from:
https://stackoverflow.com/questions/66048233/using-c-sharp-how-can-i-parse-this-string-to-a-time 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…