Convert DateTime to long and also the other way around

前端 未结 7 819
遥遥无期
遥遥无期 2020-12-05 09:29

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         


        
相关标签:
7条回答
  • 2020-12-05 09:56

    There is a DateTime constructor that takes a long.

    DateTime today = new DateTime(t); // where t represents long format of dateTime 
    
    0 讨论(0)
  • 2020-12-05 09:59

    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).

    0 讨论(0)
  • 2020-12-05 10:00
       long dateTime = DateTime.Now.Ticks;
       Console.WriteLine(dateTime);
       Console.WriteLine(new DateTime(dateTime));
       Console.ReadKey();
    
    0 讨论(0)
  • 2020-12-05 10:05

    From long to DateTime: new DateTime(long ticks)

    From DateTime to long: DateTime.Ticks

    0 讨论(0)
  • 2020-12-05 10:06

    use the pair long t = now.Ticks and DateTime Today = new DateTime(t)

    0 讨论(0)
  • 2020-12-05 10:11

    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).

    0 讨论(0)
提交回复
热议问题