gpt4 book ai didi

c# - 如何计算 c#/Code review 中两点之间的小时数

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:12 25 4
gpt4 key购买 nike

大家好,我有一个小的编程问题,它可能比我想象的要容易得多。所以我需要把下面安装Timespan opbject的时间设置为到下一个下午4点还剩24+时间。下面是C#伪代码,是用记事本写的,因为在工作中我没有IDE,我也没有太多使用日期编程的经验。我认为我的算法会起作用,但我想有更简单的方法可以做到这一点。请看:

//I need to make a timespan object which has 24 hours from current time + time left to the next 4pm

//The context is time to install, which user should see
Timespan TimeToInstall = new Timespan(23,59,59)

//Now I am taking the current time
Current = DateTime.Now

//Now I add the 24 hours to the current in order to create the next day date
Current.Add(TimeToInstall)

//Now creating the 4 PM on the next day
DateTime pm4 = new DateTime(Current.year,Current.month,Current.Day,16,0,0)

//Now checking if current is above or below 4 pm
if(Current.TimeOfDay < pm4){
TimeToInstall = TimeToInstall + (pm4 - Current)
}else if(Current.TimeOfDay > pm4){
pm4.AddDays(1)
TimeToInstall = TimeToInstall + (pm4 - Current)
}else {
//24 hours has passed and it is 4 pm so nothing to do here
}

最佳答案

TimeSpan 可以是负数。所以只需用当前 TimeOfDay 减去 4PM 的 TimeSpan ,如果得到负值,则增加 24 小时。

var timeLeft = new TimeSpan(16, 0, 0) - DateTime.Now.TimeOfDay;
if (timeLeft.Ticks<0)
{
timeLeft = timeLeft.Add(new TimeSpan(24,0,0))
}

关于c# - 如何计算 c#/Code review 中两点之间的小时数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39786968/

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