2017-10-12 76 views
2

在UWP,格式化日期作爲這樣C#DateTime.Parse(的longdate)拋出異常

string myDateString = new DateTimeFormatter("longdate").Format(DateTime.Today); 

一個的longdate串給出myDateString = "‎Thursday‎, ‎12‎ ‎October‎ ‎2017"

試圖將其轉換回這樣

DateTime myDate = DateTime.Parse(myDateString, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal); 

投擲System.FormatException

試圖將其轉回這樣

DateTime myDate = DateTime.ParseExact(myDateString, "longdate", CultureInfo.CurrentCulture); 

也會引發System.FormatException

我然後我的機器設置爲美國。值myDateString = "‎Thursday‎, ‎October‎ 12‎ ‎‎2017"

但是當我嘗試它將其轉換回日期時間這也會拋出一個System.FormatException

我應該如何將長日期字符串轉換爲C#中使用當前文化的日期時間?

+0

什麼是您的長日期格式?毫米/日/年?獲取日期時間,DateTime d = DateTime.Now;然後將它轉換爲你想要的任何格式的字符串,string s = d.ToString(「dd/MM/yyyy -HH:mm:ss.fff」); – JohnChris

+2

'DateTime.ParseExact'不使用'DateTimeFormatter',所以我不認爲它知道'DateTimeFormatter(「longdate」)的格式' – EpicKip

+1

我認爲這是UWP?如果是這樣,我會建議以這種方式標記它。另外,請提供您爲'myDateString'獲得的實際值。 –

回答

-1

重讀一下日期時間格式... DateTime Formats

是相關的疊後:here

基礎上的日期時間:basics

例如在使用DateTime with culture

一個基本的例子:

DateTime d = DateTime.Now; 
DateTime ut = d.ToUniversalTime(); 
// Defines a custom string format to display the DateTime value. 
// zzzz specifies the full time zone offset. 
    String format = "MM/dd/yyyy hh:mm:sszzz"; 

String utcstr = utcdt.ToString(format); 
     Console.WriteLine(utcstr); 

編輯:小控制檯應用程序,例如

static void Main(string[] args) 
     { 
      string myDateString = "Thursday, 12 October 2017"; 
      //Why use the above just get a new one for today in the correct format 
      //Or create your own converter 
      DateTime date = DateTime.Now; 

      CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture; 
      //or 
      var culture = System.Globalization.CultureInfo.CurrentCulture; 

      string test = currentCulture.ToString(); 

      Console.WriteLine(date.ToString(CultureInfo.GetCultureInfo(test))); 
      Console.ReadLine(); 
     } 
+0

謝謝你的建議@JohnChris,但我們不能指定一個日期格式,因爲我們必須使用的文化用戶機器。 – Vague

+0

@Vague我把一些編輯文化,你可以嘗試 – JohnChris

+0

再次感謝@約翰克里斯,但我們沒有使用UTC。我們使用本地機器的文化......無論在哪裏。 – Vague

0
string sd = "‎Thursday‎,‎ ‎October‎ 12, ‎2017"; 
sd = DateTime.Now.ToString("dddd, MMMM dd, yyyy", new CultureInfo("en-US")); 
DateTime myDate; 
if (DateTime.TryParseExact(sd,"dddd, MMMM dd, yyyy", new CultureInfo("en-US"), DateTimeStyles.None, out myDate)) 
{ 
    Console.WriteLine(myDate); //if format accepted. 
} 
+0

創建的標準長日期格式,您的解決方案不是獨立於文化的。參考上面的評論。看來這是一個UWP問題。 – Vague

+0

是的,如果你像CultureInfo((int)CultureTypes.AllCultures)那樣使用CultureInfo,那麼我認爲哪種文化是無關緊要的。 – deniz

0

@Jay佐在Cannot convert string to DateTime in uwp

當我們使用DateTimeFormatter.Format方法

解釋,也有一些無形的8206個字符在其返回值。

那麼作爲@Corak建議,不要使用DateTimeFormatter,使用ToString("D")