2016-09-30 51 views
1

大家好我有一个小编程问题,这可能比我想象的要容易得多。所以我需要设置时间来安装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 
} 
+1

温馨提示:您可以使用[C#PAD](HTTP:// csharppad .com /)在浏览器中写智能书写片段 – Martheen

+0

@Martheen谢谢,不知道 –

+1

Hello Robert ...我在代码中注意到了一件事。正如Martheen的好主意所示,DateTime和TimeSpan对象是不可变的。在添加24小时的行上:Current.Add(TimeToInstall)并不真正改变Current。它会返回一个新的DateTime对象,并添加额。它应该是Current = Current.Add(TimeToInstall)。 – JohnG

回答

2

TimeSpan可能是负值。因此,只需将TimeSpan与当前的TimeOfDay相减即可,如果您得到负值,请添加24小时。

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

基于您的代码:

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; 
0

答案其实很简单,我应该由图可见这点。这些问题的解决方案基本上是模块化算术。客户需求是弹出显示24+时间到下午4点(不要问我不知道),所以如果:

程序运行在13:00然后时钟应该显示24 +3 = 27

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

时22:00它shoould是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); 
} 
相关问题