1
votes

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 not get the time part. Can someone please tell me how to parse this into the DateTime object?

6
Please show us the code you're using to parse this date - because when I test this, it works perfectly. (Are you sure you aren't outputting the result in short date format, for instance?)Dan J
@djacobson: My apologies. My printing was messed up! You are right. It works correctly.Legend

6 Answers

5
votes

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);
1
votes

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?

1
votes

DateTime.Parse("1987-04-03 19:17:12.000") returns 4/3/1987 7:17:12 PM

0
votes

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

0
votes

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
0
votes
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime.ParseExact(timeString, "dd/MM/yyyy HH:mm:ss.fff",culture);