I have to convert a string value into TimeSpan. But its showing an error.
String was not recognized as a valid TimeSpan.
The code is:
TimeSpan _time = TimeSpan.Parse("08:55 AM");
I know it can parse the string value in "08:55". But I don't need that. I have to use AM or PM in the string.
In the database, the column datatype is time(7) and I am using entity framework.
The SQL Time datatype does not store the time of day; instead, it stores the time as the number of milliseconds since midnight.
Converting the AM version of "08:55" to a timespan is equivalent to saying "8 hours and 55 minutes since midnight", while the PM version would be "20:55", "20 hours and 55 minutes since midnight". The TimeSpan object doesn't do this calculation intrinsically, but you can simulate the result.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
DateTime timespan = DateTime.Parse("08:55 AM"); //gives us a DateTime object
DateTime timespan2 = DateTime.Parse("08:55 PM");
TimeSpan _time = timespan.TimeOfDay; //returns a TimeSpan from the Time portion
TimeSpan _time2 = timespan2.TimeOfDay;
Console.WriteLine(_time);
Console.WriteLine(_time2);
}
}
https://dotnetfiddle.net/XVLVPl
Since "08:55 AM" is a specific time not a span, it is failing to parse. However, it sounds like you may want the time since midnight, or noon depending on whether it is AM or PM
So I see 2 approaches here. One, is to strip the AM/PM from the time before parsing. as in:
string timeValue = "08:55 AM";
TimeSpan _time = TimeSpan.Parse(timeValue.Replace(" AM", "").Replace(" PM", ""));
Or you could use the DateTime.Parse and use the TimeOfDay property.
string timeValue = "08:55 AM";
TimeSpan _time = DateTime.Parse(timeValue).TimeOfDay;
if (_time > TimeSpan.FromHours(12)) _time -= TimeSpan.FromHours(12);
I prefer the second approach.
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