Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

datetime - Using C# How can I parse this string to a Time

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
if (Results.TimeOfDay != "-" || Results.TimeOfDay != null)

This will always be true, because you are asking if .TimeOfDay, or "09:00:00-09:30:00", is not equal to "-". You should use Results.TimeOfDay.Contains("-") instead.

Also,

@"h:mm tt"

This should be @"hh:mm:tt"

Edit: sorry should be @"hh:mm:ss"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...