如何正确地将日,小时和分钟添加到现有日期

时间:2015-08-06 21:43:47

标签: c#

  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方法,datetime变量保持不变。我知道当我使用.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);

3 个答案:

答案 0 :(得分:2)

看起来你想要添加任意数量的天,小时和分钟,但是要走很长的路。你可以一次完成这一切:

DateTime finalDateTime = serviceEntry.ServiceDateTime
    .AddDays(serviceday)
    .AddHours(servicehour)
    .AddMinutes(serviceminute);

答案 1 :(得分:1)

您需要分配Convert.ToInt32次调用的结果,否则不会设置变量,例如:

serviceDay = Convert.ToInt32(ServiceDay)

答案 2 :(得分:1)

你可以编写更多紧凑的代码

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);

(注意:这个答案的大部分来自DavidG,它应该拿到学分,只是为了修复那些噪音的ifs块来发现你是否有一个有效的值)