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

标签 c# datetime time timespan

大家好,我有一个小的编程问题,它可能比我想象的要容易得多。所以我需要把下面安装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/

相关文章:

c# - 在 C# 中从子域/其他域加载图像

javascript - 如何在 Angular 中按日期字符串(昨天、今天、本月、上个月)进行过滤

postgresql - postgres - 使用和不使用 TIMEZONE 参数设置显示时间戳列

javascript - 使用 JS 在浏览器支持下转换过去的日期时间

javascript - jquery 显示基于获取第二个时钟的图像

c# - 我怎样才能像正则表达式一样找到网站链接

c# - Google Drive .NET SDK 版本 3 - 可共享链接

c# - 使用 C# 查询日期时间的 MongoDb 查询

time - 客户端unix时间有多准确?

memory - 在 Go 中分析内存时看似不一致的结果