Click here to Skip to main content
15,898,588 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi
I need to calculate between two date in asp.net text box.

mean 22.04.2018 12.00 pm to 23.04.2018 12.00 pm should be calculate = one day

Pls advice me

Maideen

What I have tried:

If True Then
    Dim dt1 As DateTime = Convert.ToDateTime(Me.txtDateFrom.Text)
    Dim dt2 As DateTime = Convert.ToDateTime(Me.txtDateTo.Text)
    Dim ts As TimeSpan = dt2.Subtract(dt1)
    If Convert.ToInt32(ts.Days) >= 0 Then
        Me.txtNoDays.Text = Convert.ToInt32(ts.Days) + 1
    ElseIf dt1 = dt2 Then
        Me.txtNoDays.Text = "Invalid Input"
    End If
End If
Posted
Updated 1-Aug-18 4:15am
v3

Take off the "+ 1" from the calculation...

But also, don't use Convert operations on user input: always use the appropriate TryParse (or TryParseExact) method instead. Users always type the wrong thing, and your app shouldn't crash as a result. Displaying an error message instead and giving them a change to fix the error is much more friendly!
 
Share this answer
 
In addition to solution #1 by OriginalGriff, check this:
VB.NET
Dim s1 = "22.04.2018 12.00 pm"
Dim s2 = "23.04.2018 12.00 pm"

Dim ci As Globalization.CultureInfo = Globalization.CultureInfo.InvariantCulture 
Dim fmt As String = "dd.MM.yyyy HH.mm tt"
Dim dt1 As DateTime = DateTime.Now
Dim dt2 As DateTime = DateTime.Now
Try
	dt1 = DateTime.ParseExact(s1, fmt, ci)
	dt2 = DateTime.ParseExact(s2, fmt, ci)
Catch Ex As Exception
	Console.WriteLine(Ex.Message)
End Try

Dim dayspassed As Integer = dt2.Subtract(dt1).Days
Console.WriteLine("Difference between '{0}' and '{1}' is: {2} day(s)", dt2.ToString("yyyy-MM-dd"), dt1.ToString("yyyy-MM-dd"), dayspassed)


For further details, please see:
How to: convert strings to DateTime | Microsoft Docs[^]
DateTime.ParseExact Method (String, String, IFormatProvider) (System)[^]
Performing arithmetic operations with dates and times | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900