1

I use a TypeConverter to convert DateTime instances to and from strings.

When using the culture dependent functions ConvertTo/FromString it seems that the seconds and milliseconds parts of the DateTime don't get converted.

When using the culture invariant functions ConvertTo/FromInvariantString the milliseconds are still missing. Either way the two DateTime instances before and after the conversion are never equal, as I would have expected.

This class demonstrates the effect:

using System;
using System.ComponentModel;

public class DateToStringConversionTest 
{
    public static void Main()
    {
        TypeConverter tc = TypeDescriptor.GetConverter(typeof(DateTime));
        DateTime d1 = new DateTime( 2010, 1, 2, 3, 4, 5, 6 );

        // convert to / from invariant string
        string   s3 = tc.ConvertToInvariantString(d1);
        DateTime d3 = (DateTime) tc.ConvertFromInvariantString(s3);
        Console.WriteLine( "invariant string\n   {0}\n=> {1}\n=> {2}\n=> equals? {3}", 
              d1, s3, d3, d1.Equals(d3) );

        // convert to / from string
        string   s2 = tc.ConvertToString(d1);
        DateTime d2 = (DateTime) tc.ConvertFromString(s2);
        Console.WriteLine( "\nstring\n   {0}\n=> {1}\n=> {2}\n=> equals? {3}", 
              d1, s2, d2, d1.Equals(d2) );
    }
}

This is the output:

string
02.01.2010 03:04:05 => 02.01.2010 03:04 => 02.01.2010 03:04:00 => equals? False
invariant string
02.01.2010 03:04:05 => 01/02/2010 03:04:05 => 02.01.2010 03:04:05 => equals? False

I'm running on the German locale, so the dates are output as DD.MM.YYYY.

0

1 Answer 1

0

I usually use DateTime.Parse/TryParse and DateTime.ToString() which doesn't cut of milliseconds. I don't see the reason why this wouldn't work for you either.

1
  • Same problem here: d1.Equals( DateTime.Parse( d1.ToString() ) ) returns False
    – miasbeck
    Nov 14, 2010 at 10:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.