问题
Very basic question regarding parsing date in F#. I am very new to F# and .NET, so please bear with me.
My date has the format yyyyMMDD
like 20100503
.
How do I parse this into a DateTime
type in F#.
I tried System.DateTime.Parse("20100503");
but get an error.
How do I pass a format string into the Parse method??
ANSWER is - Thanks everyone for the responses.
let d = System.DateTime.ParseExact("20100503", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
回答1:
You should be able to use a custom format string. Try this:
System.DateTime.ParseExact("20100503", "yyyymmdd", null);;
See http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx for more details.
回答2:
DateTime.ParseExact("20100503", "yyyyMMdd", CultureInfo.CurrentCulture)
Use the ParseExact method and use lowercase d instead of upper.
回答3:
I answered a similar question this morning. I have not used F#, but if you have access to DateTime.ParseExact, my answer might help you.
You might also consider TryParseExact so that you can trap a failure based on the function returning false rather than having to put it inside of a 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.
}
回答4:
The format is not one that is accepted.
http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
You might need to manipulate the string before parsing.
you are on the right track though.
回答5:
You'll need to use the overload of DateTime.Parse which takes an IFormatProvider. The IFormatProvider you supply must understand that format.
You can do this by creating a DateTimeFormatInfo object with the correct format for the date string you are feeding to parse.
This is probably a lot of work for what you're doing. If you can reorganize the string a little first (most likely to a date string with seperators), you'll probably be better off.
来源:https://stackoverflow.com/questions/4158077/f-parse-dates