加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么Convert.ToDateTime(Int64)失败?

发布时间:2020-12-15 08:43:39 所属栏目:百科 来源:网络整理
导读:为什么以下失败/“从’Int64’到’DateTime’的无效转换.”例外? long oldDate=new DateTime(2015,1,1).Ticks;DateTime newDate=Convert.ToDateTime(oldDate); .Ticks是long / Int64,Convert.ToDateTime(Int64)MSDN文档显示接受long / Int64的方法. public
为什么以下失败/“从’Int64’到’DateTime’的无效转换.”例外?
long oldDate=new DateTime(2015,1,1).Ticks;
DateTime newDate=Convert.ToDateTime(oldDate);

.Ticks是long / Int64,Convert.ToDateTime(Int64)MSDN文档显示接受long / Int64的方法.

public static DateTime ToDateTime(
  long value
)

编辑:
如下面的ebyrob所指出的那样应该是:

long oldDate=new DateTime(2015,1).Ticks;
DateTime newDate=new DateTime(oldDate);

解决方法

从Convert.ToDateTime方法(Int64)上的MSDN文档:

Calling this method always throws InvalidCastException.

Return Value
Type: System.DateTime
This conversion is not supported. No value is returned.

来源:http://msdn.microsoft.com/en-us/library/400f25sk.aspx(链接指向.NET 4.5文档,但对于低至2.0的所有版本,它都是相同的).

我不确定为什么不支持这一点,特别是如果新的DateTime(oldDate)运行良好:

DateTime newDate = new DateTime(oldDate);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读