How do I convert a 12 hour time string into a C# T

2019-01-24 03:36发布

问题:

When a user fills out a form, they use a dropdown to denote what time they would like to schedule the test for. This drop down contains of all times of the day in 15 minute increments in the 12 hour AM/PM form. So for example, if the user selects 4:15 pm, the server sends the string "4:15 PM" to the webserver with the form submittion.

I need to some how convert this string into a Timespan, so I can store it in my database's time field (with linq to sql).

Anyone know of a good way to convert an AM/PM time string into a timespan?

回答1:

You probably want to use a DateTime instead of TimeSpan. You can use DateTime.ParseExact to parse the string into a DateTime object.

string s = "4:15 PM";
DateTime t = DateTime.ParseExact(s, "h:mm tt", CultureInfo.InvariantCulture); 
//if you really need a TimeSpan this will get the time elapsed since midnight:
TimeSpan ts = t.TimeOfDay;


回答2:

Easiest way is like this:

var time = "4:15 PM".ToTimeSpan();

.

This takes Phil's code and puts it in a helper method. It's trivial but it makes it a one line call:

public static class TimeSpanHelper
{        
    public static TimeSpan ToTimeSpan(this string timeString)
    {
        var dt = DateTime.ParseExact(timeString, "h:mm tt", System.Globalization.CultureInfo.InvariantCulture);            
        return dt.TimeOfDay;
    }
}


回答3:

Try this:

DateTime time;
if(DateTime.TryParse("4:15PM", out time)) {
     // time.TimeOfDay will get the time
} else {
     // invalid time
}


回答4:

I like Lee's answer the best, but acermate would be correct if you want to use tryparse. To combine that and get timespan do:

    public TimeSpan GetTimeFromString(string timeString)
    {
        DateTime dateWithTime = DateTime.MinValue;
        DateTime.TryParse(timeString, out dateWithTime);
        return dateWithTime.TimeOfDay;
    }


回答5:

Try:

string fromServer = <GETFROMSERVER>();
var time = DateTime.Parse(fromServer);

That gets you the time, if you create the end time as well you can get Timespans by doing arithmetic w/ DateTime objects.



标签: c# timespan