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

喜你入骨 提交于 2019-12-18 03:58:16

问题


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.



来源:https://stackoverflow.com/questions/4661232/how-do-i-convert-a-12-hour-time-string-into-a-c-sharp-timespan

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!