Link to home
Start Free TrialLog in
Avatar of RahnLev
RahnLev

asked on

a simple way to Subtract "dd/mm/yyyy" in javascript.

I need to subtract string date from another string date, the the string format is:
"dd/mm/yyyy", this needs to be done in Javascript,
I'm looking for a simple and efficient way to do this.
Avatar of Kin Fat SZE
Kin Fat SZE
Flag of Hong Kong image

you could use
re = new RegExp("[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}");
depend on your goal whether is able one decimal of day and month

<script language="javascript">
 
var strdate = '12:12:00 pm 12/12/2009 abc testing';
re = new RegExp("[0-9]{2}/[0-9]{2}/[0-9]{4}"); 
var newstr = strdate.replace(re, "");
document.write("newstr : " + newstr);
</script>

Open in new window

Avatar of RahnLev
RahnLev

ASKER

I mean that I beed to get  the value of:
15/02/2009 - 13/02/2009 = 2

2 is what I need.
ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RahnLev

ASKER

Does not let me use the new key word.
What do you mean?

Here is a function

function diff(strDate1,strDate2) {
  var arrDate1 = strDate1.split("/");
  var arrDate2 = strDate2.split("/");
  var d1 = new Date(arrDate1[2],arrDate1[1]-1,arrDate1[0],0,0,0)
  var d2 = new Date(arrDate2[2],arrDate2[1]-1,arrDate2[0],0,0,0)
  var diffInMilli = d2.getTime()-d1.getTime();
  var diffInDays = diffInMilli/(24*60*60*1000)
  return diffInDays
}
var beginDate = "13/11/2009"
var endDate = "15/11/2009"
alert(diff(beginDate,endDate))

Open in new window

Try this one from https://www.experts-exchange.com/questions/20483408/Looking-for-DateDiff-Function-in-JavaScript.html
<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<TITLE></TITLE>
<SCRIPT LANGUAGE=javascript>
<!--
function dateDifference(strDate1,strDate2){
     datDate1= Date.parse(strDate1);
     datDate2= Date.parse(strDate2);
     alert((datDate2-datDate1)/(24*60*60*1000))
     
}
//-->
</SCRIPT>
 
</HEAD>
<BODY>
 
<FORM action="" method=POST id=form1 name=form1><P>&nbsp;</P>
<INPUT type="text" id=text1 name=text1>
<INPUT type="text" id=text2 name=text2>
<INPUT type="button" value="Button" id=button1 name=button1 onClick=dateDifference(this.form.text1.value,this.form.text2.value)>
</FORM>
</BODY>
</HTML>

Open in new window

Sunithair, Date.parse does not work with european formatted dates

javascript:alert(new Date(Date.parse("13/11/2009")))