我如何轉換字符串:如何解析包含GMT的字符串到DateTime?
string aa ="Thu Jul 02 2015 00:00:00 GMT+0100 (GMT Standard Time)";
成日期時間。
我試圖使用Convert.ToDateTime(aa);
但沒有工作 謝謝。
編輯:錯誤信息 - 該字符串未被識別爲有效的DateTime
我如何轉換字符串:如何解析包含GMT的字符串到DateTime?
string aa ="Thu Jul 02 2015 00:00:00 GMT+0100 (GMT Standard Time)";
成日期時間。
我試圖使用Convert.ToDateTime(aa);
但沒有工作 謝謝。
編輯:錯誤信息 - 該字符串未被識別爲有效的DateTime
您可以使用DateTime.TryParseExact
以正確的格式字符串:
string dtString = "Thu Jul 02 2015 00:00:00 GMT+0100";
string format = "ddd MMM dd yyyy HH:mm:ss 'GMT'K";
DateTime date;
bool validFormat = DateTime.TryParseExact(dtString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
Console.Write(validFormat ? date.ToString() : "Not a valid format");
如果字符串最後包含(GMT Standard Time)
,則可以先將其刪除:
dtString = dtString.Replace("(GMT Standard Time)", "").Trim();
或使用該格式模式:
string format = "ddd MMM dd yyyy HH:mm:ss 'GMT'K '(GMT Standard Time)'";
進一步的信息:既然你有你的字符串的UTC offsethttps://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
使用DateTime.Parse方法:
using System;
public class Example
{
public static void Main()
{
string[] dateStrings = {"2008-05-01T07:34:42-5:00",
"2008-05-01 7:34:42Z",
"Thu, 01 May 2008 07:34:42 GMT"};
foreach (string dateString in dateStrings)
{
DateTime convertedDate = DateTime.Parse(dateString);
Console.WriteLine("Converted {0} to {1} time {2}",
dateString,
convertedDate.Kind.ToString(),
convertedDate);
}
}
}
// These calls to the DateTime.Parse method display the following output:
// Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
// Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
// Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM
嘗試過'DateTime convertedDate = DateTime.Parse(aa);'引發異常:'字符串未被識別爲有效的DateTime'。 – captainsac
,我寧願解析DateTimeOffset
,而不是DateTime
。而且沒有辦法解析你的GMT
和(GMT Standard Time)
部件而不能逃脫它們。
DateTime
和DateTimeOffset
都是時區感知順便說一下。對於這種情況,DateTimeOffset
略好於DateTime
。它具有UTC偏移量,但不能保證時區信息,因爲不同的時區可以具有相同的偏移值。
即使它們是,時區縮寫也不標準化。例如,CST
有幾個含義。
string s = "Thu Jul 02 2015 00:00:00 GMT+01:00 (GMT Standard Time)";
DateTimeOffset dto;
if (DateTimeOffset.TryParseExact(s, "ddd MMM dd yyyy HH:mm:ss 'GMT'K '(GMT Standard Time)'",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dto))
{
Console.WriteLine(dto);
}
現在,你有一個DateTimeOffset
爲{02.07.2015 00:00:00 +01:00}
MSDN'DateTime.Parse'包含了你需要的所有信息。 – atlaste
它怎麼沒用?任何錯誤消息?意外的行爲? – wonderb0lt