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?
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.
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.
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
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With