Reputation: 2230
I am trying to use DateTime.ParseExact on a timestamp that uses the format M/d/yyyy HH:mm:ss:fff
and the compiler is telling me that this is not going to happen.
An example of my timestamp is:
3/26/2013 14:37:05:553
...and an example of my code is, where _CultureInfo is en-us.
DateTime someDateTime = DateTime.ParseExact("3/26/2013 14:37:05:553","M/d/yyyy HH:mm:ss:fff", _CultureInfo.DateTimeFormat);
See below image of what's going on... am I missing something?
New Edit
I've tried a couple more things with still no luck:
:fff
to .fff
_CultureInfo.DateTimeFormat
to System.Globalization.CultureInfo.InvariantCulture
and changing the d
to dd
as suggested belowBelow is something you can throw into a Console and run to see exactly how this is behaving on my end.
class Program
{
static void Main(string[] args)
{
CsvImporter importer = new CsvImporter();
DateTime readtime = importer.Parse(@"""3/26/2013 14:37:07:238,00:00:01.6850000,23.138,23.488,23.175""");
Console.WriteLine(readtime.ToString());
}
}
class CsvImporter
{
public Char[] _SeparatorChars = new Char[] { ',' };
public DateTime Parse(string text)
{
System.Globalization.CultureInfo _CultureInfo = System.Globalization.CultureInfo.CurrentCulture;
string txt = text.Replace('"', ' ');
string[] columns = txt.Split(_SeparatorChars);
return DateTime.ParseExact(columns[0], "M/dd/yyyy HH:mm:ss:fff", _CultureInfo.DateTimeFormat);
//return DateTime.ParseExact(columns[0], "M/dd/yyyy HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture);
}
}
Upvotes: 2
Views: 3177
Reputation: 2230
The issue is with string txt = text.Replace('"', ' ');
This is turning column[0]
into [space]3/26/2013 14:37:05:553
instead of 3/26/2013 14:37:05:553
like I'd expect.
Changing this line to string txt = text.Replace(@"""", "");
solves the problem.
Upvotes: 1
Reputation: 40393
Whenever you call ParseExact
, make sure you're using an unambiguous format string. In .NET, the /
character in a format string is the system date separator, not an actual slash. Same for the :
character in times.
To parse a string with your structure, escape out the slashes and colons with backslashes, like:
DateTime.ParseExact(s, @"M\/d\/yyyy HH\:mm\:ss\:fff", null)
// or
DateTime.ParseExact(s, "M\\/d\\/yyyy HH\\:mm\\:ss\\:fff", null)
This will tell the parser that you specifically want the forward-slash and colon, regardless of your system preferences or current culture.
Upvotes: 0
Reputation: 35353
Try this (Changed d
to dd
and CultureInfo.InvariantCulture
)
DateTime someDateTime = DateTime.ParseExact("3/26/2013 14:37:05:553", "M/dd/yyyy HH:mm:ss:fff", CultureInfo.InvariantCulture);
Upvotes: 4