1gn1ter
1gn1ter

Reputation: 1444

The resut of comparison of the same DateTime value gives 'false'

var expected = DateTime.Now;
var value = expected.ToString();

Assert.AreEqual(expected.Ticks, DateTime.Parse(value).Ticks);

Assert.AreEqual failed. Expected:<634590535915492841>. Actual:<634590535910000000>.

Why this is happening?

Upvotes: 3

Views: 229

Answers (4)

Austin Salonen
Austin Salonen

Reputation: 50245

DateTime.Ticks are equal to 100 nanoseconds. Given that the restored Ticks value ends in 7 zeroes means that all sub-second details were lost in the ToString call.

You will need to use a ToString format that yields the precision you need.

var expected = DateTime.Now;
var value = expected.ToString("yyyy-MM-dd HH:mm:ss.fffffffzzz");

Assert.AreEqual(expected.Ticks, DateTime.Parse(value).Ticks);

The important part of the code above is the set of 7 f's. This yields 7-digit precision on the fractional seconds, which is exactly what was lost on the default ToString call.

I built the format string with information from this MSDN page on DateTimeFormatInfo.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1504072

When you call ToString() like that, you'll get the default format for the current thread's culture. If you want to round-trip the value, you'll need to use an appropriate format - and indeed there's a format specified designed specifically for the job:

using System;

class Program
{
    static void Main(string[] args)
    {
        DateTime now = DateTime.Now;
        string text = now.ToString("o");
        DateTime parsed;
        if (DateTime.TryParseExact(text, "o", null,
            DateTimeStyles.RoundtripKind, out parsed))
        {
            Console.WriteLine(parsed == now);
        }
        else
        {
            Console.WriteLine("Couldn't parse");
        }
    }
}

Upvotes: 2

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112772

You can use The Round-trip ("O", "o") Format Specifier in order to preserve all the information contained in DateTime:

string value = expected.ToString("o");

Upvotes: 0

Bashwork
Bashwork

Reputation: 1619

Because you are using the default ToString which doesn't include ticks in the format.

Upvotes: 7

Related Questions