如何计算c#/代码审查中两点之间的小时数

本文关键字:之间 两点 小时 代码审查 何计算 计算 | 更新日期: 2023-09-27 18:09:50

大家好,我有一个小编程问题,这可能比我想象的要容易得多。所以我需要设置时间安装下面的时间跨度对象为24 +时间剩下的下一个下午4点。下面是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
}

如何计算c#/代码审查中两点之间的小时数

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))
}

根据您的代码:

DateTime now = DateTime.Now; 
DateTime today4pmDateTime= new DateTime(now.Year, now.Month, now.Day, 16, 0, 0);
//Will hold the next 4pm DateTime.
DateTime next4pmDateTimeOccurrence = now.Hour >= 16 ?  today4pmDateTime : today4pmDateTime.AddDays(1);
//From here you can do all the calculations you need
TimeSpan timeUntilNext4pm =  next4pmDateTimeOccurrence  - now;

答案很简单,我应该早点看到的。这类问题的解决方法基本上是模算法。客户要求弹出窗口显示24+时间到下一个下午4点(不要问我不知道),所以如果:

程序在13:00运行,那么时钟应该显示24 +3 = 27

当16:00时,它应该是24+24,也就是48

22:00时应该是24 + 18,也就是42

现在我注意到:

13 + 27 = 40

16 + 24 = 40

22 + 18 = 40

40模24 = 16

基本上,如果我用40减去当前时间就会得到差值:

40 - 13 = 27

40 - 16 = 24

40 - 22 = 18

我所做的是:

TimeSpan TimeToInstall;                
TimeSpan TimeGiven = new TimeSpan(23, 59, 59);        
DateTime Now = DateTime.Now;
long TimeTo4 = (new TimeSpan(40, 0, 0).Ticks - Now.TimeOfDay.Ticks) + TimeGiven.Ticks;
TimeToInstall = TimeSpan.FromTicks(TimeTo4);

编辑以上是一个陷阱

纠正:

DateTime Now = DateTime.Now;
if (Now.Hour < 16)
{
    long TimeTo4 = (new TimeSpan(40, 0, 0).Ticks - Now.TimeOfDay.Ticks);
    TimeToInstall = TimeSpan.FromTicks(TimeTo4);
}
else
{
    long TimeTo4 = (new TimeSpan(40, 0, 0).Ticks - Now.TimeOfDay.Ticks) + TimeGiven.Ticks;
    TimeToInstall = TimeSpan.FromTicks(TimeTo4);
}