NSDate Function cant accept a null value

NOVATROOP77 266 Reputation points
2021-08-30T13:31:22.7+00:00

Is there a way to make this function accept a null datetime ?. By that I mean ToNSDate I have attempted it with my overide method but when I simply place Datetime? in an overide obv TotalSeconds does not exist.

namespace Microsoft.Maui
{
  public static class DateExtensions
  {
    internal static DateTime ReferenceDate = new DateTime(2001, 1, 1, 0, 0, 0);

    public static DateTime ToDateTime(this NSDate date)
    {
        return ReferenceDate.AddSeconds(date.SecondsSinceReferenceDate);
    }

    public static NSDate ToNSDate(this DateTime? date)
    {   
       return NSDate.FromTimeIntervalSinceReferenceDate((date - ReferenceDate).TotalSeconds);           
    }

     public static NSDate ToNSDate(this DateTime date)
     {  
       return NSDate.FromTimeIntervalSinceReferenceDate((date - ReferenceDate).TotalSeconds);           
     }
 }
}

I called like this from the function

public static void UpdateDate(this MauiDatePicker nativeDatePicker, IDatePicker datePicker, UIDatePicker? picker)
{
            if (picker != null && picker.Date.ToDateTime().Date != datePicker.Date?.Date)
                picker.SetDate(datePicker.Date.ToNSDate(), false);

            nativeDatePicker.Text = datePicker.Date?.ToString(datePicker.Format);

            nativeDatePicker.UpdateCharacterSpacing(datePicker);
}
Developer technologies .NET Xamarin
Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2021-08-30T14:17:10.207+00:00

    Try making a single function instead of two:

    public static NSDate ToNSDate( this DateTime? date )
    {
       if( date == null ) return null;
    
       return NSDate.FromTimeIntervalSinceReferenceDate( ( date.Value - ReferenceDate ).TotalSeconds );
    }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.