简体   繁体   中英

DateTime.Ticks for nullable 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

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 .

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();
if (article.DatePublished.HasValue)
{
      list.Add(article.DatePublished.Value.Ticks);
}

If you always want to add a value, including a default if DatePublished is null, you could do something like

var date = article.DatePublished ?? new DateTime(whatever);
list.Add(date.Ticks);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM