我想找到两个DateTime值之间的总天数。所以我创建了执行减法的totaldays:
TimeSpan totaldays = enddatedata - startdatedata;
我想将TimeSpan四舍五入到第一个整数,例如13而不是13:00:00:00,因为我想将值13添加到数据库中。出于测试目的,我使用标签来显示结果:
lbltotaldays.Text = (totaldays.ToString());
如何将值四舍五入到第一个数字?
protected void insertbutton_Click(object sender, EventArgs e)
{
int? recurrencedata = Convert.ToInt32(ddlRecurrence.Text);
if (recurrencedata == 1)
{
int moduledata = Convert.ToInt32(ddlModule.Text);
DateTime startdatedata = Convert.ToDateTime(txtstartdate.Text);
DateTime enddatedata = Convert.ToDateTime(txtenddate.Text);
int classtypedata = Convert.ToInt32(ddlClassType.Text);
int roomcodedata = Convert.ToInt32(ddlRoomCode.Text);
int starttimedata = Convert.ToInt32(ddlStartClassTime.Text);
int endtimedata = Convert.ToInt32(ddlEndClassTime.Text);
startdatedata = DateTime.Parse(txtstartdate.Text).Date;
enddatedata = DateTime.Parse(txtenddate.Text).Date;
TimeSpan totaldays = enddatedata - startdatedata;
string DefaultConnection = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection myConnection = new SqlConnection(DefaultConnection);
myConnection.Open();
string query = "INSERT INTO Class (ModuleId, ClassTypeId, ClassScheduleStartTimeId, ClassScheduleEndTimeId, RoomCodeId, StartTime, EndTime, RecurrenceId, TotalDayNumber) VALUES ( @moduledata, @classtypedata, @starttimedata, @endtimedata, @roomcodedata, @startdatedata, @enddatedata, @recurrencedata, @totaldaynumberdata)";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@moduledata", moduledata);
myCommand.Parameters.AddWithValue("@classtypedata", classtypedata);
myCommand.Parameters.AddWithValue("@startdatedata", startdatedata);
myCommand.Parameters.AddWithValue("@enddatedata", enddatedata);
myCommand.Parameters.AddWithValue("@starttimedata", starttimedata);
myCommand.Parameters.AddWithValue("@roomcodedata", roomcodedata);
myCommand.Parameters.AddWithValue("@endtimedata", endtimedata);
myCommand.Parameters.AddWithValue("@recurrencedata", recurrencedata);
myCommand.Parameters.AddWithValue("@totaldaynumberdata", totaldays);
myCommand.ExecuteNonQuery();
myConnection.Close();
SuccessPanel.Visible = true;
lbltotaldays.Text = (totaldays.ToString());
}
}
}
答案 0 :(得分:1)
如果您希望从TimeSpan
获取完整天数,请使用其Days
属性:
lbltotaldays.Text = totaldays.Days.ToString();
这将忽略小时数,因此,例如,13天22小时5分钟将产生13
。
如果您想将13½天视为14天,请致电TotalDays
财产上的Math.Round
:
lbltotaldays.Text = ((int)Math.Round(totaldays.TotalDays, MidpointRounding.AwayFromZero)).ToString();