If I have a string that is in the format yyyyMMddHHmmssfff
for example 20110815174346225
. how would I create a DateTime object from that String.
I tried the following
DateTime TimeStamp = DateTime.Parse(Data[1], "yyyyMMddHHmmssfff");
However I get these errors:
Error 1 The best overloaded method match for 'System.DateTime.Parse(string, System.IFormatProvider)' has some invalid arguments C:\Documents and Settings\rkelly1\Desktop\开发者_如何学Csd\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs 67 29 WindowsFormsApplication1
Error 2 Argument 2: cannot convert from 'string' to 'System.IFormatProvider' C:\Documents and Settings\rkelly1\Desktop\sd\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs 67 53 WindowsFormsApplication1
var sDate = "20110815174346225";
var oDate = DateTime.ParseExact(sDate, "yyyyMMddHHmmssfff", CultureInfo.CurrentCulture);
You would have to use
DateTime time = DateTime.ParseExact(String,String, IFormatProvider);
The first argument string is going to be your date. The second argument string is going to be your format The third argument is your culture info (which is the IFormatProvider
So you would have
DateTime TimeStamp = DateTime.ParseExact(Data[1],"yyyyMMddHHmmssfff",CultureInfo.InvariantCulture);
The culture info is "A CultureInfo object that represents the culture used to interpret s. The DateTimeFormatInfo object returned by its DateTimeFormat property defines the symbols and formatting in s." From MSDN.
here's the link for more info. http://msdn.microsoft.com/en-us/library/kc8s65zs.aspx
Use DateTime.ParseExact
:
DateTime dateTime = DateTime.ParseExact("[Your Date Here]",
"yyyyMMddHHmmssfff",
CultureInfo.InvariantCulture);
Here's the MSDN Docs.
You should use the static method DateTime.ParseExact
.
I had a date formatted as 20151221T031901
to convert this to date time, I was able to use this format
DateTime.ParseExact("20151221T031901","yyyyMMddTHHmmss" , System.Globalization.CultureInfo.CurrentCulture)
精彩评论