Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Convert.ToDateTime(Int64) fail?

Tags:

c#

.net

datetime

Why does the following fail w/ an "Invalid cast from 'Int64' to 'DateTime'." exception?

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

.Ticks is a long/Int64 and the Convert.ToDateTime(Int64) MSDN docs show the method accepting a long/Int64.

public static DateTime ToDateTime(
  long value
)

EDIT: As pointed out by ebyrob below it should be:

long oldDate=new DateTime(2015, 1, 1).Ticks;
DateTime newDate=new DateTime(oldDate);
like image 687
ChrisP Avatar asked Oct 30 '13 23:10

ChrisP


1 Answers

From the MSDN documentation on Convert.ToDateTime Method (Int64):

Calling this method always throws InvalidCastException.

And

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

Source: http://msdn.microsoft.com/en-us/library/400f25sk.aspx (the link points to .NET 4.5 documentation but it's the same for all versions down to 2.0).

I'm not sure why this is not supported especially if new DateTime(oldDate) works well:

DateTime newDate = new DateTime(oldDate);
like image 56
Szymon Avatar answered Sep 19 '22 13:09

Szymon