将DateTime转换为long,反之亦然

Ton*_*Nam 38 .net c# datetime

我想将日期作为数字存储在表格中.我知道怎么做,但我不知道怎么回去.如何将长变量强制转换为ToDateTime.

DateTime now = DateTime.Now;
long t = now.ToFileTime();
DateTime today = t.ToDateTime;  // I am looking for something like this line. This Method does not exist
Run Code Online (Sandbox Code Playgroud)

我知道有很多方法可以将DateTime转换为long.我不介意使用哪种技术.我只想有一种方法可以来回转换.

aba*_*hev 88

从DateTime延长:

long DateTime.Ticks

从长期到日期时间:

new DateTime(long)

  • @tgarcia在一毫秒内*每秒有10,000,000个刻度 (2认同)

Jam*_*mie 9

从long到DateTime: new DateTime(long ticks)

从DateTime到long: DateTime.Ticks


Dan*_*n J 5

既然你正在使用ToFileTime,你就会想要使用FromFileTime反过来.但请注意:

通常,FromFileTime方法恢复由ToFileTime方法保存的DateTime值.但是,在以下条件下,这两个值可能会有所不同:

如果DateTime值的序列化和反序列化发生在不同的时区.例如,如果美国东部时区的时间为12:30 PM的DateTime值被序列化,然后在美国太平洋时区进行反序列化,则12:30 PM的原始值将调整为上午9:30到反映两个时区之间的差异.

如果序列化的DateTime值表示本地时区中的无效时间.在这种情况下,ToFileTime方法调整还原的DateTime值,以便它表示本地时区中的有效时间.

如果您不关心long存储DateTime的哪种表示形式,您可以Ticks像其他人所建议的那样使用(Ticks可能更好,具体取决于您的要求,因为返回的值ToFileTime似乎是在Windows文件系统API的上下文中).