大家好我有一个小编程问题,这可能比我想象的要容易得多。所以我需要设置时间来安装Timespan opbject,时间为下午4点左右。下面是C#伪代码,它是用记事本编写的,因为在工作中我没有IDE,我也没有太多使用日期编程的经验。我认为我的alghorithm将工作,但我认为有一个更简单的方法来做到这一点。请看看:如何计算C#/代码审查中两点之间的小时数
//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#PAD](HTTP:// csharppad .com /)在浏览器中写智能书写片段 – Martheen
@Martheen谢谢,不知道 –
Hello Robert ...我在代码中注意到了一件事。正如Martheen的好主意所示,DateTime和TimeSpan对象是不可变的。在添加24小时的行上:Current.Add(TimeToInstall)并不真正改变Current。它会返回一个新的DateTime对象,并添加额。它应该是Current = Current.Add(TimeToInstall)。 – JohnG