DateTime's representation in milliseconds?

后端 未结 7 964
遥遥无期
遥遥无期 2020-11-30 05:21

I have a SQL-server timestamp that I need to convert into a representation of time in milliseconds since 1970. Can I do this with plain SQL? If not, I\'ve extracted it into

7条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 05:57

    As of .NET 4.6, you can use a DateTimeOffset object to get the unix milliseconds. It has a constructor which takes a DateTime object, so you can just pass in your object as demonstrated below.

    DateTime yourDateTime;
    long yourDateTimeMilliseconds = new DateTimeOffset(yourDateTime).ToUnixTimeMilliseconds();
    

    As noted in other answers, make sure yourDateTime has the correct Kind specified, or use .ToUniversalTime() to convert it to UTC time first.

    Here you can learn more about DateTimeOffset.

提交回复
热议问题