Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Ticks for nullable datetime

Tags:

c#

datetime

In my app, article.DatePublished is a nullable DateTime field. Now I have this following code:

      list.Add(article.DatePublished.Ticks);

Here I am getting a compile error as Ticks property does not work with nullable DateTimes.

One way of handling this is:

if (article.DatePublished != null)
      list.Add(((DateTime)article.DatePublished).Ticks);

This works, but is this an elegant solution? Or can we make it "better"?

Thanks,

Vivek

like image 573
Vivek Avatar asked Dec 29 '25 06:12

Vivek


2 Answers

You need to get at the .Value property of the DateTime?.

if (nullableDate != null) // or if (nullableDate.HasValue)
    ticks = nullableDate.Value.Ticks;

You could otherwise use nullableDate.GetValueOrDefault().Ticks, which would normalize a null date into the default value of DateTime, which is DateTime.MinValue.

like image 76
Anthony Pegram Avatar answered Dec 30 '25 20:12

Anthony Pegram


As Icarus mentioned, I'd use:

if (article.DatePublished != null)
{
    list.Add(article.DatePublished.Value.Ticks);
}

Or even:

if (article.DatePublished.HasValue)
{
    list.Add(article.DatePublished.Value.Ticks);
}

Depending on what you're trying to do, it could be that LINQ will give you simpler code:

var list = articles.Select(article => article.DatePublished)
                   .Where(date => date != null)
                   .Select(date => date.Ticks)
                   .ToList();
like image 28
Jon Skeet Avatar answered Dec 30 '25 19:12

Jon Skeet