DateTime.ParseExact omitting milliseconds in C #?
I am trying to convert string to Datetime in C #. String datestring = 2013/03/18 10: 54: 07.679
-
I tried
DateTime dt=DateTime.ParseExact(datestring, "yyyy/MM/dd HH:mm:ss.fff",null);
Result: {3/18/2013 10:54:07 AM} -
I tried
DateTime.TryParseExact(datestring,"yyyy/MM/dd HH:mm:ss.fff",CultureInfo.InvariantCulture,DateTimeStyles.None,out dttt);
Result: {3/18/2013 10:54:07 AM}
In both of the above cases, ohm-million-milliseconds (679).
How can I convert it to datetime correctly while keeping milliseconds away?
source to share
This does not mean that you just check through the debugger, but the debugger shows it using AM or PM, it doenot shows the millisecond part.
Try the following:
DateTime dt=DateTime.ParseExact(datestring, "yyyy/MM/dd HH:mm:ss.fff",null);
Console.WriteLine(dt.ToString("yyyy/MM/dd HH:mm:ss.fff"));
EDIT: from your commentBut I need the answer in Datetime instead of string
You already have a DateTime including MilliSeconds
, only the debugger is not showing because (As mentioned in the comment from Ant P
) the Debugger invokes a parameterless overload ToString()
that shows DateTime
without MilliSeconds.
source to share
You should be aware that parsing the fff string will not work if the time contains a 2-digit millisecond.
for example, in my case I had 2019-08-19 13: 35: 06.27, which will not parse but 2019-08-20 13: 35: 04.274 will parse correctly. I assume this will also happen for 1-digit and 0-digit milliseconds.
This will only work if the milliseconds have trailing zeros. eg .270
Example:
string x = "2019-08-20 13:35:04.27";
DateTime d;
bool result = DateTime.TryParseExact(x, "yyyy-MM-dd HH:mm:ss.fff",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out d);
Console.WriteLine(result);
source to share