无法隐式转换类型“System.DateTime?"到“系统.日期时间".存在显式转换 [英] Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

查看:58
本文介绍了无法隐式转换类型“System.DateTime?"到“系统.日期时间".存在显式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 DateTime? 转换为 DateTime 但我收到此错误:

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

错误 7 无法隐式转换类型System.DateTime?"到'系统.日期时间'.存在显式转换

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

这是我的代码:

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;
}

推荐答案

你有 3 个选项:

1) 获取默认值

dt = datetime??DateTime.Now;

如果 datetime 为空,它将分配 DateTime.Now (或您想要的任何其他值)

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

2) 检查日期时间是否包含值,如果不包含则返回空字符串

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

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

3) 将方法的签名更改为

3) Change signature of method to

public string ConvertToPersianToShow(DateTime  datetime)

这一切都是因为 DateTime? 意味着它可以为空 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.

这篇关于无法隐式转换类型“System.DateTime?"到“系统.日期时间".存在显式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆