2016-09-30 49 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); 
} 
相關問題