C# Correct way to change DateTime value?
Is is possible to change the value returned by DateTime? Or at least assign it to a variabl开发者_如何学Ce then change that variable?
internal int hour;
internal int minute;
DateTime time = DateTime.Now;
public int incrementHour(int step)
{
if (step > 0 && hour < 24)
{
//step = step % hour;
hour = (hour + step) % 24;
time.AddHours(hour);
return hour;
}//end of if
else
{
MessageBox.Show("Please enter a positive number.");
return 0;
}//end of else
}//end of incrementHour
Addhours doesn't really do anything from the looks of it.
Instances of DateTime
are immutable - AddHours()
returns a new instance of DateTime
that reflects the changed value - so you have to re-assign the changed value to your time variable:
time = time.AddHours(hour);
MSDN for AddHours method (applies to all other methods of DateTime
as well):
This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation. The Kind property of the returned DateTime object is the same as that of value.
all you need to do is
time = time.AddHours(hour)
and that will be it
See documentation of DateTime.AddHours, it does not change the parameter value but returns a new DateTime instance. Try:
time = time.AddHours(hour);
精彩评论