如何正确添加日,小时和分钟到现有的日期
本文关键字:日期 分钟 添加 何正确 小时 | 更新日期: 2023-09-27 18:06:49
int serviceday = 0;
int servicehour = 0;
int serviceminute = 0;
if (ServiceDay == null || ServiceDay == "")
{
serviceday = 0;
}
else
Convert.ToInt32(ServiceDay);
if (ServiceHour == null || ServiceHour == "")
{
servicehour = 0;
}
else
Convert.ToInt32(ServiceHour);
if (ServiceMinute == null || ServiceMinute == "")
{
serviceminute = 0;
}
else
Convert.ToInt32(serviceminute);
我试图添加天,小时和分钟到现有的日期时间,但使用。adddays,。addhours和。addminutes方法,日期时间变量保持不变。我知道当我使用. adddays方法时,我必须为返回值分配一个新变量,即使这样也不会改变datetime变量。
DateTime servicedatetime = new DateTime();
servicedatetime = serviceEntry.ServiceDateTime;
DateTime newdatetimeDays = new DateTime();
DateTime newdatetimeHours = new DateTime();
DateTime newdatetimeMinutes = new DateTime();
newdatetimeDays = servicedatetime.AddDays(serviceday);
newdatetimeHours = newdatetimeDays.AddHours(servicehour);
newdatetimeMinutes = newdatetimeHours.AddMinutes(serviceminute);
看起来您想要添加任意数量的天数,小时和分钟,但却要绕很长一段路。您可以一次完成所有操作:
DateTime finalDateTime = serviceEntry.ServiceDateTime
.AddDays(serviceday)
.AddHours(servicehour)
.AddMinutes(serviceminute);
你可以写更紧凑的代码
int serviceday;
int servicehour;
int serviceminute;
Int32.TryParse(ServiceDay, out serviceday);
Int32.TryParse(ServiceHour, out servicehour);
Int32.TryParse(ServiceMinute, out serviceminute);
DateTime finalDateTime = serviceEntry.ServiceDateTime
.AddDays(serviceday)
.AddHours(servicehour)
.AddMinutes(serviceminute);
您需要分配Convert.ToInt32
调用的结果,否则未设置变量,例如:
serviceDay = Convert.ToInt32(ServiceDay)