-1

I am new to VB Scripting. I have two dates, date_1 and date_2. I need to subtract date_1 from date_2 and the output the difference in date format.

example:

date_1 = 01-09-2014
date_2 = 08-10-2016

output would ideally be:

= date_2 - date_1
= 08-10-2016 - 01-09-2014
= 07-01-0002

Finally i need the output like 02 years, 01 months and 07 days.

Please help me out.

Many thanks in advance.

Jason Yost
  • 4,807
  • 7
  • 42
  • 65
Nandu
  • 1
  • 1
  • 2
  • See this question to help you get started http://stackoverflow.com/questions/27030073/vbscript-datediff-month – Jason Yost Oct 08 '16 at 18:01
  • 2
    Possible duplicate of [Age calculation in years, months, days](http://stackoverflow.com/questions/34196718/age-calculation-in-years-months-days) – JosefZ Oct 08 '16 at 20:09

2 Answers2

0

Take a look at the below code:

Dim date_1, date_2, l, r(2)

date_1 = "01-09-2014"
date_2 = "08-10-2016"
l = SetLocale(2057) ' UK
Delta 0, Array("yyyy", "m", "d"), Array("years", "months", "days"), r, CDate(date_1), CDate(date_2), False
SetLocale l

MsgBox Join(r, ", ") ' 2 years, 1 months, 7 days

Sub Delta(i, t, n, r, d1, d2, c)
    Dim q, d
    q = DateDiff(t(i), d1, d2)
    If UBound(t) > i Then
        Do
            d = DateAdd(t(i), q, d1)
            Delta i + 1, t, n, r, d, d2, c
            If c Then Exit Do
            q = q - 1
        Loop
    End If
    c = q >= 0
    r(i) = q & " " & n(i)
End Sub

You even can set the date and time and compute difference up to second:

Dim date_1, date_2, l, r(5)

date_1 = "01-09-2014 10:55:30"
date_2 = "08-10-2016 15:45:10"
l = SetLocale(2057) ' UK
Delta 0, Array("yyyy", "m", "d", "h", "n", "s"), Array("years", "months", "days", "hours", "minutes", "seconds"), r, CDate(date_1), CDate(date_2), False
SetLocale l

MsgBox Join(r, ", ") ' 2 years, 1 months, 7 days, 4 hours, 49 minutes, 40 seconds

Sub Delta(i, t, n, r, d1, d2, c)
    Dim q, d
    q = DateDiff(t(i), d1, d2)
    If UBound(t) > i Then
        Do
            d = DateAdd(t(i), q, d1)
            Delta i + 1, t, n, r, d, d2, c
            If c Then Exit Do
            q = q - 1
        Loop
    End If
    c = q >= 0
    r(i) = q & " " & n(i)
End Sub
omegastripes
  • 12,351
  • 4
  • 45
  • 96
-2

Using some string functions , you can easily achieve your goal .

Hope this helps .

date_1 = InputBox("Enter first Date in format DD-MM-YYYY","Time Difference")
date_2 = InputBox("Enter second Date in format DD-MM-YYYY","Time Difference")

day_differ = Abs(CInt(Left(date_2 , 2)) - CInt(Left(date_1 , 2)))
month_differ = Abs(CInt(Mid(date_2 , 4 , 2)) - CInt(Mid(date_1 , 4 , 2)))
year_differ = Abs(CInt(Right(date_2 , 4)) - CInt(Right(date_1 , 4)))

wscript.echo "Date Difference is " & year_differ & " years, " & month_differ & " months and " & day_differ & " days."
Abhishek
  • 412
  • 5
  • 17