2016-06-18 39 views
0

我必須將字符串值轉換爲TimeSpan。但它顯示了一個錯誤。我想將字符串(「08:55 AM」)轉換爲時間範圍

字符串未被識別爲有效的TimeSpan。

的代碼是:

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

我知道它可以在"08:55"解析字符串值。但我不需要那個。我必須在字符串中使用AM或PM。 在數據庫中,列數據類型爲time(7),我使用的是entity framework

+3

'TimeSpan'是一些東西花費的時間; '「上午8:55」'不是一段時間,而是一個特定的時間。如果您有特定時間,請改用'DateTime'。 – Claies

+3

[DateTime.Parse](https://msdn.microsoft.com/en-us/library/system.datetime.parse(v = vs.110).aspx)呢? –

+0

在數據庫中,列數據類型是time(7),而我正在使用實體框架。所以我必須使用TimeSpan。 –

回答

2

可以那種字符串轉換爲時間跨度與此代碼

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

儘管這樣做確實有效,但我認爲最好了解_why_它並不適用於開箱即用。 –

+0

是的,我同意這一點。這個問題似乎有一些沒有清楚解釋的問題。如果可以使用DateTime而不是TimeSpan,會更好 – Steve

1

的SQL數據類型Time不保存一天的時間;相反,它將時間存儲爲自午夜以來的毫秒數。

將AM版本"08:55"轉換爲時間範圍相當於說「自午夜以來8小時55分鐘」,而PM版本爲"20:55"「自午夜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

1

由於「上午08點55分」是一個特定的時間不是一個跨度,它無法解析。然而,聽起來你可能想要從午夜或中午開始的時間,取決於它是AM還是PM

所以我在這裏看到2種方法。一種是從解析前的時間中去除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); 

我更喜歡第二種方法。

相關問題