簡體   English   中英

為什么 netcoreapp2.1 和 netcoreapp3.1 的 TimeSpan 值不同?

[英]Why are the TimeSpan values different between netcoreapp2.1 and netcoreapp3.1?

當我從 netcoreapp2.1 轉到 netcoreapp3.1 時,我注意到我的一些單元測試失敗了。

以下代碼有不同的結果:

using System;

namespace ConsoleApp12
{
    class Program
    {
        static void Main(string[] args)
    {
        var seconds = 0.81960;
        var timeSpan = TimeSpan.FromSeconds(seconds);

        Console.WriteLine($"seconds:{seconds}");
        Console.WriteLine($"timeSpan:{timeSpan}");
        Console.WriteLine($"timeSpan.Milliseconds:{timeSpan.Milliseconds}");
        Console.WriteLine($"timeSpan.Ticks:{timeSpan.Ticks}");
    }
    }
}

/*
core 2.1 and Framework 4.8 ROUNDS to nearest ms
seconds:0.8196
timeSpan:00:00:00.8200000
timeSpan.Milliseconds:820
timeSpan.Ticks:8200000
*/

/*
core 3.1 no longer rounds to nearest ms

seconds:0.8196
timeSpan:00:00:00.8196000
timeSpan.Milliseconds:819
timeSpan.Ticks:8196000
*/

這不是顯示格式的事情,您可以從刻度的基礎值中看到這一點。

為什么 dotnet 核心版本之間存在差異?

在 dotnet core 2.1 和 3.1 之間(大約 2019 年底), System.TimeSpan的行為發生了變化,因此工廠方法不再四舍五入到最接近的 1ms。

有一個關於這個問題的GitHub這里

注意:當前文檔尚未更新以反映行為的變化,示例代碼的輸出現在在站點上不正確: System.TimeSpan.FromSeconds

在 .net core 2.1 和 Net Framework 中,創建的 TimeSpan 被四舍五入到最接近的毫秒:

      FromSeconds          TimeSpan
      -----------          --------
            0.001          00:00:00.0010000
           0.0015          00:00:00.0020000
          12.3456          00:00:12.3460000
      123456.7898        1.10:17:36.7900000
  1234567898.7654    14288.23:31:38.7650000
                1          00:00:01
               60          00:01:00
             3600          01:00:00
            86400        1.00:00:00
        1801220.2       20.20:20:20.2000000 

在 .net core 3.1 中,它不會四舍五入到最接近的毫秒(例如 12.3456):

      FromSeconds          TimeSpan
      -----------          --------
            0.001          00:00:00.0010000
           0.0015          00:00:00.0015000
          12.3456          00:00:12.3455999
      123456.7898        1.10:17:36.7898000
  1234567898.7654    14288.23:31:38.7654000
                1          00:00:01
               60          00:01:00
             3600          01:00:00
            86400        1.00:00:00
        1801220.2       20.20:20:20.2000000

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM