Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 201
KallDrexx Avatar asked Jan 11 '11 18:01

KallDrexx


People also ask

How to convert text string to 12 hour clock in Excel?

If your text string format is 120456P, you can use this formula =TEXT (-- (LEFT (A1,LEN (A1)-1)),"0\:00\:00")+ ( (RIGHT (A1,1)="P")/2), then format the cells as the 12 hour clock you need. See screenshot: If your text string includes date and time such as 20141212 0312, you can use a little long formula to solve.

How to convert hour to a number?

As we have got individual digit of hour we will convert into a number. Check if the hh is in 12 hour or 24 hour format using if-else and set the Meridian as AM or PM. Modulo hh with 12 and convert the time into 12-hour format.

How do you convert 12 hour time to 24 hour time?

Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. Note: Midnight is 12:00:00 AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00 PM on 12-hour clock and 12:00:00 on 24-hour clock

How to convert 24-hour to 12-hour format in Python?

After changing it into integer we will modulo the hour with 12 and that will be in the 12-hour format. The case when there is 00 in the hour will be calculated as a separate case. Take the char str into the function. Obtain the first digit and second digit of the hour from the 24-hour format string.


Video Answer


2 Answers

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;
like image 61
Phil Lamb Avatar answered Sep 26 '22 06:09

Phil Lamb


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;
    }
}
like image 38
whitneyland Avatar answered Sep 24 '22 06:09

whitneyland