KallDrexx
KallDrexx

Reputation: 27803

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

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?

Upvotes: 15

Views: 19466

Answers (5)

Lee Whitney III
Lee Whitney III

Reputation: 10968

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

Upvotes: 7

Phil Lamb
Phil Lamb

Reputation: 1437

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;

Upvotes: 39

Chris
Chris

Reputation: 1148

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

Upvotes: 2

acermate433s
acermate433s

Reputation: 2544

Try this:

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

Upvotes: 3

Chris Pfohl
Chris Pfohl

Reputation: 19054

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.

Upvotes: 1

Related Questions