Difference between DateTimeOffset? (Nullable) and DateTimeOffset.Now

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

I want a result like "x day y hours ago"

I started 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 find the difference.

+3


source to share


3 answers


Depending on what difference you expect from a NULL database value, you can simply handle it with the operator ??

:

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

      



(can of course be shortened to use ??

only when reading a database value)

+7


source


First check if the value is relevant HasValue

and if it uses the property Value

to get the actual value

if(creationTime.HasValue)
    TimeSpan difference = DateTimeOffset.Now.Subtract(creationTime.Value);

      

Or, if you have a default, you can use GetValueOrDefault

TimeSpan difference = DateTimeOffset.Now.Subtract(creationTime.GetValueOrDefault(default));

      



The final option would be to just use the operator -

.

TimeSpan? difference = DateTimeOffset.Now - creationTime;

      

but note what difference

will TimeSpan?

and will be null

if creationTime

null

.

+3


source


Just in case someone comes across this issue, here is an extension method I came up with using the answers above.

namespace Extensions{
public static class DateExtensions
{
    public static string GetDifferenceTillNow(this DateTimeOffset? datetimeoffset) {
        DateTimeOffset? creationTime = datetimeoffset;
        DateTimeOffset rightnow = DateTimeOffset.Now;
        DateTimeOffset somewhen = creationTime ?? rightnow;
        TimeSpan difference = rightnow.Subtract(somewhen);
        return difference.Days.ToString() +" days & " +  difference.Hours.ToString() + " hours ago";
    }
  }
}

      

0


source







All Articles