如何避免.NET中从Unix时间戳转换为DateTime并返回的精度损失



考虑以下片段

var original = new DateTime(635338107839470268);
var unixTimestamp = (original - new DateTime(1970,1,1)).TotalSeconds;
// unixTimestamp is now 1398213983.9470267
var back = new DateTime(1970,1,1).AddSeconds(1398213983.9470267);
// back.Ticks is 635338107839470000 

正如你所看到的,我们得到的Ticks值与我们开始时的值不同。

在从日期转换为unix时间戳并返回时,我们如何避免C#中的精度损失?

http://msdn.microsoft.com/en-us/library/system.datetime.addseconds.aspx

每个文档的DateTime.AddSeconds()四舍五入到最接近的毫秒(10000个刻度)。

使用记号:

// We have a DateTime in memory
DateTime original = new DateTime(635338107839470268);
// We convert it to a Unix Timestamp
double unixTimestamp = (original - new DateTime(1970, 1, 1)).TotalSeconds;
// unixTimestamp is saved somewhere
// User needs to make a 100% precise DateTime from this unix timestamp
DateTime epochInstance = new DateTime(1970, 1, 1);
DateTime back = epochInstance.AddTicks((long)(unixTimestamp * TimeSpan.TicksPerSecond));
// back.Ticks is now 635338107839470268

时间跨度没有损失,不要与TotalSeconds和AddSeconds方法的结果进行比较。你需要检查Ticks

var original = new DateTime(635338107839470268);
var Ticks = (original - new DateTime(1970,1,1)).Ticks;
// Ticks is now 13982139839470268
var back = new DateTime(1970,1,1).AddTicks(13982139839470268);
//back.Ticks is 635338107839470268

相关内容

  • 没有找到相关文章

最新更新