Muhammad Awais
Muhammad Awais

Reputation: 4492

I am trying to convert string("08:55 AM") into timespan

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.

Upvotes: 4

Views: 8597

Answers (3)

Steve
Steve

Reputation: 216293

You can convert that kind of strings to a TimeSpan with this code

TimeSpan _time;
string input = "08:55 PM";
string[] fmts = new string[] {@"hh\:mm\ \A\M", @"hh\:mm\ \P\M"};
if(TimeSpan.TryParseExact(input, fmts, CultureInfo.InvariantCulture, out _time))
{
    if(input.EndsWith("PM"))
       _time = _time.Add(new TimeSpan(12,0,0));
    Console.WriteLine(_time.ToString());        
}

Upvotes: 2

NebulaSleuth
NebulaSleuth

Reputation: 841

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.

Upvotes: 3

Claies
Claies

Reputation: 22323

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

Upvotes: 6

Related Questions