简体   繁体   中英

Adding Minutes to Date is not changing the Date C# .NET

double TotalMinute=300.0 double TotalMinutesAdded=1378.0


double TotalMinute=300.0
double TotalMinutesAdded=1378.0

foreach(DataRow dr in ds.Tables[0].Rows)
                {

                    //Add The above Timings to each Row's 2nd Column
                    DateTime correctDate=Convert.ToDateTime(dr[2]);

                    correctDate.AddMinutes(TotalMinute);
                    correctDate.AddMinutes(TotalMinutesAdded);

                    dr[2]=correctDate;

                }

DateTiem Add* functions are not supposed to change current DateTime value. They RETURN the new Value.

If you want your value changed, type like this:

correctDate = correctDate.AddMinutes(TotalMinute);

DateTime is immutable; functions like AddMinutes return a new DateTime; so you need to catch the returned value:

DateTime foo = ...
DateTime bar = foo.AddMinutes(5);

As mentioned, due to DateTime objects being immutable you have to reassign the variable.

However, a point to note is that you can chain the manipulations as so:

correctDate = correctDate.AddMinutes(TotalMinute)
                         .AddMinutes(TotalMinutesAdded);

您必须将correctDate变量设置为从AddMinutes调用返回的实例:

correctDate = correctDate.AddMinutes(TotalMinute);

DateTime is an immutable type, much like String is. You would write date = date.AddDays(1) like you would write str = str.Replace("hello", "").

...and to add say 5 minutes to the current time to a datetime variable:

dim dateFive_Minute_Time as datetime

dateFive_Minute_Time = Now.AddMinutes(5)

AddMinutes() does not change the value of the original DateTime. It returns a new DateTime with the new value that you have to assign to a variable.

The problem lies with

correctDate.AddMinutes(TotalMinute); 
correctDate.AddMinutes(TotalMinutesAdded);

it should be

correctDate = correctDate.AddMinutes(TotalMinute); 
correctDate = correctDate.AddMinutes(TotalMinutesAdded);

The AddMinutes method returns the result, not adding the minutes to correctDate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM