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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With