簡體   English   中英

F# - 解析日期

[英]F# - Parse dates

關於在F#中解析日期的非常基本的問題。 我是F#和.NET的新手,所以請耐心等待。

我的日期格式為yyyyMMDD20100503

如何將其解析為F#中的DateTime類型。

我試過System.DateTime.Parse("20100503"); 但得到一個錯誤。

如何將格式字符串傳遞給Parse方法?

答案是 - 感謝大家的回復。

let d = System.DateTime.ParseExact("20100503", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);

您應該能夠使用自定義格式字符串。 試試這個:

System.DateTime.ParseExact("20100503", "yyyymmdd", null);;

有關詳細信息,請參閱http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

DateTime.ParseExact("20100503", "yyyyMMdd", CultureInfo.CurrentCulture)

使用ParseExact方法並使用小寫d代替upper。

我今天早上回答了類似的問題 我沒有使用過F#,但是如果你有權訪問DateTime.ParseExact,我的回答可能對你有幫助。

您可能還會考慮TryParseExact,以便您可以根據返回false的函數捕獲失敗,而不必將其放在try catch中:

//Using code example from my previous answer...
string s = "100714 0700"; 
DateTime d;
if (!DateTime.TryParseExact(s, "yyMMdd hhmm", CultureInfo.InvariantCulture, out d))
{
  // Whoops!  Something is wrong with the date.
}


//In your case
string s = "20100503"; 
DateTime d;
if (!DateTime.TryParseExact(s, "yyyyMMdd", CultureInfo.InvariantCulture, out d))
{
  // Whoops!  Something is wrong with the date.
}

格式不是被接受的格式。

http://msdn.microsoft.com/en-us/library/1k1skd40.aspx

您可能需要在解析之前操作字符串。

你是在正確的軌道上。

您需要使用帶有IFormatProvider的DateTime.Parse的重載。 您提供的IFormatProvider必須了解該格式。

您可以通過使用正在為要解析的日期字符串的正確格式創建DateTimeFormatInfo對象來執行此操作。

對於你正在做的事情,這可能是很多工作。 如果你可以先重新組織字符串(最有可能是一個帶分隔符的日期字符串),你可能會更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM