Extract date from string and perform difference

Hi,
I have two strings which has date and time. I need to extract dates from both strings and perform subtraction. Example

str1 = 10/20/2022 1:42:00 PM
str2 = 11/10/2022 1:42:00 PM

date1 = 10/20/2022
date2 = 11/10/2022

difference=date2-date1, which is 21 days

Thanks in advance

See this thread from today with the same issue written slightly differently

Thanks for your response.None is working for me. when I’m trying to extract date and convert into datetime/date, along with date I’m getting time as well like 10/20/2022 00:00:00 where i need only 10/20/2022

Yeah that’s the difference between a Date and a DateTime
If they both parse with the time being zero - then subtracting them would return the same as if the time portion wasn’t there, right?

Anyway if that bothers you, you could parse it to Date instead of DateTime and use DateDiff as in:

Dim date2Entered As String = InputBox("Enter a date")

Try
    Dim date2 As Date = Date.Parse(date2Entered)
    Dim date1 As Date = Now

    ' Determine the number of days between the two dates.
    Dim days As Long = DateDiff(DateInterval.Day, date1, date2)

    ' This statement has a string interval argument, and
    ' is equivalent to the above statement.
    'Dim days As Long = DateDiff("d", date1, date2)

    MessageBox.Show("Days from today: " & days.ToString)
Catch ex As Exception
    MessageBox.Show("Invalid Date: " & ex.Message)
End Try

Hey @Kavya_Mamidishetti2,

Could you try out the below code

DateValue(“10/20/2022”)-DateValue(“11/10/2022”)
i am getting the value as -21 as shown in the screenshot below you can then extract it out from there by splitting it based on : and getting the first value. Let me know if it works out
image

Regards.

Hi,

you can also try,
int_DateDifference = Convert.ToDateTime(date1).Subtract(Convert.ToDateTime(date2))

Please mark it as solution if it solves your issue

Thanks

2 Likes

Use the below method

endDate=Convert.ToDateTime(DateTime.ParseExact("11/10/2022 1:42:00 PM", "MM/dd/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture).ToString("MM/dd/yyyy"))
startDate=Convert.ToDateTime(DateTime.ParseExact("10/20/2022 1:42:00 PM", "MM/dd/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture).ToString("MM/dd/yyyy"))
TotalDays = Convert.ToInt32((endDate-startDate).TotalDays)

Variable Type

Way of Implementation
image

Output
image

Thanks,
Sanjit

1 Like