大家好我有一個小編程問題,這可能比我想象的要容易得多。所以我需要設置時間來安裝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