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

…衆ロ難τιáo~ 提交于 2019-11-29 03:38:46
Phil Lamb

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;

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;
    }
}

Try this:

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

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;
    }

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.

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