[英]How to convert string to date time
string value = "Sat Apr 28 2012 11:00:00 GMT-0400 (Eastern Daylight Time)"
我需要轉換為日期時間
我試着做:
DateTime datetime = DateTime.ParseExact(value, "MM/dd/yyyy hh:mm", null);
要么
DateTime datetime2 = Convert.ToDateTime(value);
例外:字符串未被識別為有效的DateTime。
您指定的格式為“ MM / dd / yyyy hh:mm”,但字符串的格式甚至略有不同 。
我懷疑您在使用“ GMT-0400(東部夏令時間)”時會遇到麻煩-其余部分的格式為“ ddd MMM dd yyyy HH:mm:ss”或“ ddd MMM d yyyy HH:mm:ss” ”,如果月份中的日期並非總是兩位數。
我建議您分別從UTC解析偏移量,並創建一個DateTimeOffset
將第一部分(在GMT之前)解析為未指定的 DateTime
然后解析該偏移量。 編輯:您可以使用TimeSpan.ParseExact
解析偏移量,但您需要自己處理符號,我相信-我看不到有任何記錄這種方式來解析負時間跨度的方法:(
編輯:請注意,我的Noda Time項目將允許您解析偏移量部分,例如使用“'GMT'+ HHmm”模式-顯然我們會處理LocalDateTime
部分-但您仍然需要分開字符串的不同部分。 樣例代碼:
using System;
using System.Linq;
using System.Xml.Linq;
using NodaTime;
using NodaTime.Text;
public class Test
{
static void Main()
{
string text = "Sat Apr 28 2012 11:00:00 GMT-0400 (Eastern Daylight Time)";
ZonedDateTime parsed = Parse(text);
Console.WriteLine(parsed);
}
static readonly LocalDateTimePattern LocalPattern =
LocalDateTimePattern.CreateWithInvariantInfo("ddd MMM d yyyy HH:mm:ss");
// Note: Includes space before GMT for convenience later
static readonly OffsetPattern OffsetPattern =
OffsetPattern.CreateWithInvariantInfo("' GMT'+HHmm");
static ZonedDateTime Parse(string text)
{
int gmtIndex = text.IndexOf(" GMT");
int zoneIndex = text.IndexOf(" (");
// TODO: Validation that these aren't -1 :)
string localText = text.Substring(0, gmtIndex);
string offsetText = text.Substring(gmtIndex, zoneIndex - gmtIndex);
var localResult = LocalPattern.Parse(localText);
var offsetResult = OffsetPattern.Parse(offsetText);
// TODO: Validate that both are successful
var fixedZone = DateTimeZone.ForOffset(offsetResult.Value);
return localResult.Value.InZoneStrictly(fixedZone);
}
}
請注意,這將在固定時區(不是真正的東部時間)中給出ZonedDateTime
。 目前Noda Time沒有OffsetDateTime
,這在這里很自然。
請嘗試以下操作:
Convert.ToDateTime("Sat Apr 28 2012 11:00:00 GMT-0400 (Eastern Daylight Time)".Substring(4, 20))
您的字符串與您的格式不匹配。
您需要先分析該字符串,然后再嘗試對其進行轉換。 例如,可以解析“ Apr 28 2012 11:00:00”。 但是,您需要自己轉換其余部分。
您可能想研究使用此處記錄的 DateTimeOffset
,因為它可以保存相對於UTC的時間,例如您的字符串。
發現這是文檔,與您所擁有的非常接近
// Parse date and time with custom specifier.
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
try
{
result = DateTimeOffset.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
Console.WriteLine("{0} is not in the correct format.", dateString);
}
嘗試ddd MMM d yyyy hh:mm:ss zzz
如果不起作用,請嘗試此
如果您查看Custom Date and Time Format Strings ,那么您所得到的只是該格式的一種變體:
"ddd MMM dd yyyy h:mm:ss zzz"
里面只有一些額外的部分:
"ddd MMM dd yyyy h:mm:ss GMTzzz (blah blah blah)"
如果您處理這些問題,應該沒問題:
value = value.Remove(value.IndexOf(" ("));
DateTime datetime = DateTime.ParseExact(value, "ddd MMM dd yyyy hh:mm:ss \"GMT\"zzz", null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.