Skip to main content
rakeshk21205956
Inspiring
May 20, 2020
Answered

Need to Calculate difference between 2 dates in YEAR , MONTH & DAYS

  • May 20, 2020
  • 1 reply
  • 3072 views

I need the difference between 2 dates  in three different field:

In first field :  it should in Years

   2nd Field :  it should be Month,

  3rd Field :  it should be Days

 

For ex-  First Date: 14/05/1998   second date: 18/04/2019 

difference should show   1st Field:   20 years 

                                        2nd Field : 11 months

                                      3rd Field :   04 days

 

I searched regarding this on this community and found few scripts, accordingly i converted the full difference in milliseconds.. and converted them to days, months, year.. everything works fine

but days are not calculated correctly due to 30,31, 28,29 days and in month due leap year.

 

Below are the scripts used after the difference is converted to milliseconds (TotalTime_MS)

for day field:

event.value = Math.floor((this.getField("TotalTime_MS").value)/(1000*60*60*24)%365.25);

 

For Month Field:

event.value = Math.floor( ((this.getField("TotalTime_MS").value)/(1000*60*60*24*30))%12 );

 

For Year Field:

event.value = Math.floor((this.getField("TotalTime_MS").value)/(1000*60*60*24*365.25));

 

 

Thanks in advance

 

This topic has been closed for replies.
Correct answer try67

Sure, it's possible. You need to first convert the strings to Date objects, and then use that object's various functions to figure out the difference between the dates. All of the necessary functions are documented here: https://www.w3schools.com/jsref/jsref_obj_date.asp

 

1 reply

try67
Community Expert
Community Expert
May 20, 2020

This is not a math issue, but a definitions issue. You need to define what you mean by "years" and "months".

As you've seen, the length of both of those can vary, so you need to clearly define what should be the result for all possible combinations, and based on that write the logic for your calculation.

rakeshk21205956
Inspiring
May 21, 2020

Obviously YEAR mean CALENDAR YEAR  and same with MONTH means CALENDAR MONTH.

Is that not possible in JavaScript..... is year and month are not specified in Javascript.

try67
Community Expert
try67Community ExpertCorrect answer
Community Expert
May 21, 2020

Sure, it's possible. You need to first convert the strings to Date objects, and then use that object's various functions to figure out the difference between the dates. All of the necessary functions are documented here: https://www.w3schools.com/jsref/jsref_obj_date.asp