Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I lose milliseconds of a DateTime when it's passed to a method which takes Nullable DateTime?

I have a constructor method similar to this:

public class Foo
{
 public Foo (DateTime? startFrom)
        {
            _startFrom = startFrom;
        }
}

And I am calling this constructor method like this:

   var context = new Foo(new DateTime(2012, 7, 15, 11, 2, 10, 2)); // 2 miliseconds

But when I debug it, I find that the 002 milliseconds are set to 000 when passed to the default constructor which is a Nullable DateTime parameter.

Is it normal that I lose the milliseconds of a DateTime when I pass it as a parameter to a method which takes Nullable DateTime?

like image 391
pencilCake Avatar asked Jun 22 '12 08:06

pencilCake


People also ask

Can DateTime be nullable?

DateTime is by default not a nullable type. So it can never store null value.

How does DateTime work in C#?

C# includes DateTime struct to work with dates and times. To work with date and time in C#, create an object of the DateTime struct using the new keyword. The following creates a DateTime object with the default value. The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight).

How do I pass a date as NULL in C#?

C# Nullable Type By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. Using a question mark (?) after the type or using the generic style Nullable.


2 Answers

No, it's not normal - and I strongly suspect that this is a diagnostics issue.

When you debug through the code, I suspect you're using a watch window which happens not to display the milliseconds in its string representation. Expand the variable itself and I'm sure you'll see the milliseconds component is preserved.

(If that's not the case, please provide a short but complete program which demonstrates the problem, rather than just the snippet you've shown.)

like image 111
Jon Skeet Avatar answered Sep 22 '22 16:09

Jon Skeet


I just tried it and I do get the milliseconds. How are you verifying this?

I ran it in debug mode and inspected your context._startFrom.Millisecond it has the value of 2.

Are you relying on ToString() output? That does not by default show milliseconds.

like image 40
Simon Ejsing Avatar answered Sep 25 '22 16:09

Simon Ejsing