How can I parse this date format into a DateTime object?
I have a date of the following format in a file (YYYY-MM-DD HH:MM:SS.millisecs):
1987-04-03 19:17:12.000
When I use DateTime to parse this string, it gets only the date part and does n开发者_运维问答ot get the time part. Can someone please tell me how to parse this into the DateTime object?
Use DateTime.ParseExact().
var format = "yyyy-MM-dd hh:mm:ss.fff"
var dt = DateTime.ParseExact(s, format);
See http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx. You should also add a format provider, just as CultureInfo.InvariantCulture.
var dt = DateTime.ParseExact(s, format, CultureInfo.InvariantCulture);
I did up a quick console app and it's showing both date and time:
string dateTimeString = "1987-04-03 19:17:12.000";
Console.WriteLine(DateTime.Parse(dateTimeString));
Console.ReadLine();
The resulting output is: 4/3/1987 7:17:12 PM
You might be using the resulting parse value incorrectly?
DateTime.Parse("1987-04-03 19:17:12.000") returns 4/3/1987 7:17:12 PM
The format string you are looking for is:
yyyy-MM-dd HH:mm:ss.fff
So
DateTime myDateTime = DateTime.ParseExact(sourceString, "yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvarientCulture);
See MSDN for more information
How are you parsing it? How are you converting the DateTime to a string?
DateTime date = DateTime.Parse ("1987-04-03 19:17:12.000");
Console.WriteLine (date);
// yields: 4/3/1987 7:17:12 PM
Console.WriteLine (date.Date);
// yields: 4/3/1987
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime.ParseExact(timeString, "dd/MM/yyyy HH:mm:ss.fff",culture);
精彩评论