我试图将字符串(“08:55 AM”)转换为时间跨度

时间:2016-06-18 17:39:17

标签: c# asp.net entity-framework time

我必须将字符串值转换为TimeSpan。但它显示错误。

  

字符串未被识别为有效的TimeSpan。

代码是:

TimeSpan _time = TimeSpan.Parse("08:55 AM");

我知道它可以解析"08:55"中的字符串值。但我不需要那个。我必须在字符串中使用AM或PM。 在数据库中,列数据类型为time(7),我正在使用entity framework

3 个答案:

答案 0 :(得分:2)

您可以使用此代码将此类字符串转换为TimeSpan

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

答案 1 :(得分:1)

SQL Time数据类型不存储一天中的时间;相反,它将时间存储为自午夜以来的毫秒数。

"08:55"的AM版本转换为时间跨度相当于说“"从午夜开始的8小时55分钟”#34;而PM版本将是"20:55",&#34 ;自午夜起20小时55分钟" TimeSpan对象本身并不进行此计算,但您可以模拟结果。

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

答案 2 :(得分:1)

从" 08:55 AM"是一个特定的时间而不是跨度,它无法解析。但是,听起来你可能想要从午夜或中午开始的时间,具体取决于它是AM还是PM

所以我在这里看到了两种方法。一,是从解析​​之前剥离AM / PM。如:

string timeValue = "08:55 AM";
TimeSpan _time = TimeSpan.Parse(timeValue.Replace(" AM", "").Replace(" PM", ""));

或者您可以使用DateTime.Parse并使用TimeOfDay属性。

string timeValue = "08:55 AM";
TimeSpan _time = DateTime.Parse(timeValue).TimeOfDay;
if (_time > TimeSpan.FromHours(12)) _time -= TimeSpan.FromHours(12);

我更喜欢第二种方法。