Difference between DateTimeOffset?(Nullable) and DateTimeOffset.Now

nishantvodoo picture nishantvodoo · Jul 31, 2015 · Viewed 11.8k times · Source

How can I calculate the time between between a nullable DateTimeOffset? to DateTimeOffset.Now ?

I need the result like "x day y hours ago"

I started by doing something like this.

  var creationTime = //A nullable DateTimeOffset on Database    
  var difference = DateTimeOffset.Now.Subtract(creationTime);

But since creationTime is a nullable time, it gives me an error and I can't really find the difference.

Answer

Filburt picture Filburt · Jul 31, 2015

Depending on what difference you expect from a NULL database value you can simply handle this using the ?? operator:

DateTimeOffset? creationTime = null; // A nullable DateTimeOffset on Database
DateTimeOffset rightnow = DateTimeOffset.Now;
DateTimeOffset somewhen = creationTime ?? rightnow; // if NULL, it's NOW
var difference = rightnow.Subtract(somewhen);

(could of course be shortend to using ?? just when reading the database value)