gpt4 book ai didi

c# - 如何使用字符串格式将时差四舍五入到最接近的秒数?

转载 作者:行者123 更新时间:2023-11-30 13:30:09 24 4
gpt4 key购买 nike

我正在尝试减去 2 个日期时间并以分钟和秒的格式获取时差,但如何以字符串格式将时差四舍五入到最接近的秒数。

我有如下日期:

1)

StartDate= 2016-10-11 04:31:06.513  EndDate=  2016-10-11 04:31:09.457  
Differrence : 2.94
Output I am getting is : 00 : 02
Expected Output : 00 : 03 (round up time to the nearest)

2)

StartDate = 2016-10-14 16:43:18.530 EndDate= 2016-10-14 16:43:50.457 
Difference : 31.93
Output I am getting is : 00 : 31
Expected Output : 00 : 32 (round up time to the nearest)

这是下面的 linq 查询,我正在尝试计算时差:

var output = Attendance.Select
(
t => new
{
TimeDifference = string.Format("{0:00}:{1:00}", (int)t.EndDateTime.Value.Subtract(t.StartDateTime.Value).Minutes, (int)t.EndDateTime.Value.Subtract(t.StartDateTime.Value).Seconds),
}
).ToList()

enter image description here

最佳答案

正如 Dawnkeeper 在他的回答中所说,您必须使用 Math.Ceiling , 而不是获取 Seconds 属性,您必须使用 TimeSpan.TotalSeconds ,像这样:

var TimeDifference = string.Format("{0:00}:{1:00}", (int)EndDateTime.Subtract(StartDateTime).Minutes, (int)Math.Ceiling(EndDateTime.Subtract(StartDateTime).TotalSeconds));

编辑Henrik 是对的,上面的代码不起作用。让我们做对:

var diff=EndDateTime.Subtract(StartDateTime);
double seconds= Math.Ceiling(diff.Seconds+diff.Milliseconds*0.001);
var TimeDifference = string.Format("{0:00}:{1:00}",diff.Minutes,seconds);

我现在在用手机,所以我不能尝试,但我认为它应该可以工作

关于c# - 如何使用字符串格式将时差四舍五入到最接近的秒数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40042745/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com