I want to store dates as numbers in a table. I know how to do that but I don\'t know how to go back. How can I cast a long variable to ToDateTime.
DateTime n
There is a DateTime constructor that takes a long.
DateTime today = new DateTime(t); // where t represents long format of dateTime
There are several possibilities (note that the those long values aren't the same as the Unix epoch.
For your example (to reverse ToFileTime()
) just use DateTime.FromFileTime(t)
.
long dateTime = DateTime.Now.Ticks;
Console.WriteLine(dateTime);
Console.WriteLine(new DateTime(dateTime));
Console.ReadKey();
From long to DateTime: new DateTime(long ticks)
From DateTime to long: DateTime.Ticks
use the pair long t = now.Ticks and DateTime Today = new DateTime(t)
Since you're using ToFileTime
, you'll want to use FromFileTime to go the other way. But note:
Ordinarily, the FromFileTime method restores a DateTime value that was saved by the ToFileTime method. However, the two values may differ under the following conditions:
If the serialization and deserialization of the DateTime value occur in different time zones. For example, if a DateTime value with a time of 12:30 P.M. in the U.S. Eastern Time zone is serialized, and then deserialized in the U.S. Pacific Time zone, the original value of 12:30 P.M. is adjusted to 9:30 A.M. to reflect the difference between the two time zones.
If the DateTime value that is serialized represents an invalid time in the local time zone. In this case, the ToFileTime method adjusts the restored DateTime value so that it represents a valid time in the local time zone.
If you don't care which long
representation of a DateTime is stored, you can use Ticks
as others have suggested (Ticks is probably preferable, depending on your requirements, since the value returned by ToFileTime
seems to be in the context of the Windows filesystem API).