如何计算两个日期之间的日期?

时间:2012-05-20 07:41:07

标签: asp.net vb.net datetime

我有2个文本框,txtStartDate.Text和txtEndDate.Text,用户通过日历日期选择器选择日期。 现在我想计算两个选定日期之间的天数,并将结果保存在数据库字段totalDay(类型整数)中,以下是我的代码:

但是当我点击按钮并尝试将其保存到数据库中时,我收到此错误:

正在使用的SQL Server版本不支持数据类型“time”。

我该怎么做才能解决这个问题?

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Threading
Imports System.Globalization

Partial Class addevent
Inherits System.Web.UI.Page

Protected Sub ButtonAddEvent_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ButtonAddEvent.Click

    Dim connString As String = ConfigurationManager.ConnectionStrings("ConnectionString1").ConnectionString
    '"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\eventdb.mdf;Integrated Security=True;User Instance=True"
    Dim con As SqlConnection = New SqlConnection(connString)

    Dim cmdQuery As String = "INSERT INTO eventinfo(venue,totalDay,eventTitle,startDate,endDate,description) VALUES (@venue,@totalDay,@eventTitle,@startDate,@endDate,@description)"
    Dim cmd = New SqlCommand(cmdQuery)
    cmd.Connection = con
    cmd.CommandType = CommandType.Text
    con.Open()
    cmd.Parameters.AddWithValue("@eventTitle", txtEventTitle.Text)
    cmd.Parameters.AddWithValue("@venue", txtEventLocation.Text)
    cmd.Parameters.AddWithValue("@startDate", txtStartDate.Text)
    cmd.Parameters.AddWithValue("@endDate", txtEndDate.Text)
    cmd.Parameters.AddWithValue("@description", txtEventDescription.Text)

    Dim fmt As String = "dd/MM/yyyy"
    Dim dtStart As DateTime = DateTime.ParseExact(txtStartDate.Text, fmt, Nothing)
    Dim dtEnd As DateTime = DateTime.ParseExact(txtEndDate.Text, fmt, Nothing)

    Dim ts As TimeSpan = dtEnd - dtStart

    cmd.Parameters.AddWithValue("@totalDay", ts.TotalDays)


    cmd.ExecuteNonQuery()
    cmd.Parameters.Clear()
    con.Close()

    Response.Redirect("~/addbooth.aspx")

End Sub
End Class

我的表结构: enter image description here

3 个答案:

答案 0 :(得分:0)

由于您的字段是整数类型,并且您只允许用户输入没有时间组件的日期,因此可以使用以下内容:

cmd.Parameters.AddWithValue("@totalDay", ts.Days)

TimeSpan.TotalDays为您提供天数和分数天数,TimeSpan.Days仅为整天。

答案 1 :(得分:0)

尝试在SQL命令参数列表中添加SQL DataBase Type,如下所示。

示例代码

cmd.Parameters.Add("ParameterName", SqlDbType.Date).Value = "Value";

答案 2 :(得分:0)

使用此:

Dim totalday As Integer = DateDiff(DateInterval.Day, <Date_1> , <Date_2>)