Calculate 6 Months from Current Date using SQL Query, C# and VB.Net in ASP.Net

Last Reply 6 days ago By pandeyism

Posted 6 days ago

How do I calculate 6 months from today

Here is the concept i have used

6 * 30 = 180

DATEADD(DateInterval.Day, 180, Date.Parse("03-Apr-2019")

It gives me 29 Sep 2019

But the correct one is 2 October 2019 for 6 months

how can i get this 2 October 2019 

Posted 6 days ago

Hi satabeach,

Refer below sample.

HTML

Calculated Date :
<asp:Label ID="lblDate" runat="server" />

Namespaces

C#

using System.Data.SqlClient;
using System.Data;
using System.Configuration;

VB.Net

Imports System.Data.SqlClient
Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        string query = "SELECT CONVERT(VARCHAR,DATEADD(MONTH, 6, DATEADD(DAY,-1,[Date])),106) AS [Date] FROM TestDate";
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    lblDate.Text = dt.Rows[0]["Date"].ToString();
                }
            }
        }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim query As String = "SELECT CONVERT(VARCHAR,DATEADD(MONTH, 6, DATEADD(DAY,-1,[Date])),106) AS [Date] FROM TestDate"
        Using con As SqlConnection = New SqlConnection(constr)
            Using cmd As SqlCommand = New SqlCommand(query, con)
                Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
                    Dim dt As DataTable = New DataTable()
                    da.Fill(dt)
                    lblDate.Text = dt.Rows(0)("Date").ToString()
                End Using
            End Using
        End Using
    End If
End Sub

Output

Calculated Date : 02 Oct 2019