Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

I am trying to convert DateTime? to DateTime but I get this Error:

Error 7 Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

Here is my code:

public string ConvertToPersianToShow(DateTime?  datetime)
{
  DateTime dt;
  string date;
  dt = datetime;
    
  string year = Convert.ToString(persian_date.GetYear(dt));
  string month = Convert.ToString(persian_date.GetMonth(dt));
  string day = Convert.ToString(persian_date.GetDayOfMonth(dt));
    
  if (month.Length == 1)
  {
     month = "0" + Convert.ToString(persian_date.GetMonth(dt));
  }
  if (day.Length == 1)
  {
     day = "0" + Convert.ToString(persian_date.GetDayOfMonth(dt));
  }

  //date = Convert.ToString(persian_date.GetYear(dt)) + "/" + 
  Convert.ToString(persian_date.GetMonth(dt)) + "/" +
  //Convert.ToString(persian_date.GetDayOfMonth(dt));
  date = year + "/" + month + "/" + day+"("+dt.Hour+":"+dt.Minute+")";

  return date;
}

You have 3 options:

1) Get default value

dt = datetime??DateTime.Now;

it will assign DateTime.Now (or any other value which you want) if datetime is null

2) Check if datetime contains value and if not return empty string

if(!datetime.HasValue) return "";
dt = datetime.Value;

3) Change signature of method to

public string ConvertToPersianToShow(DateTime  datetime)

It's all because DateTime? means it's nullable DateTime so before assigning it to DateTime you need to check if it contains value and only then assign.


dt is nullable you need to access its Value

if (datetime.HasValue)
    dt = datetime.Value;

It is important to remember that it can be NULL. That is why the nullablestruct has the HasValue property that tells you if it is NULL or not.

You can also use the null-coalescing operator ?? to assign a default value

dt = datetime ?? DateTime.Now;

This will assign the value on the right if the value on the left is NULL


The problem is that you are passing a nullable type to a non-nullable type.

You can do any of the following solution:

A. Declare your dt as nullable

DateTime? dt = dateTime;

B. Use Value property of the the DateTime? datetime

DateTime dt = datetime.Value;

C. Cast it

DateTime dt = (DateTime) datetime;