Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

c# - 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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...