Link to home
Start Free TrialLog in
Avatar of aviator21114
aviator21114

asked on

Convert text variables containing mm-dd-yyyy to a date format so I can compare

Uncle, I cry uncle....  I've browsed a bunch of code and can't seem to hone in on what I need.

I have two date variables let's call them date1 date2.  they are strings always in the format of mm-dd-yyyy.    All I want to do is determine the number of days between these two dates.  I'm pretty sure I first need to convert these to another format but I'm not sure how to code this... can someone show me the javascript code to do this?

Thanks,
Avatar of Gary
Gary
Flag of Ireland image

<script>
date1="12-01-2013"
date2="12-12-2013"

// get the parts of the date
date1=date1.split("-");
date2=date2.split("-");

// rebuild the date so js understands it and convert to millisecs
date1=new Date(date1[2], date1[0] - 1, date1[1]).getTime();
date2=new Date(date2[2], date2[0] - 1, date2[1]).getTime();

// difference between the dates in millisecs
var difference = Math.abs(date1 - date2)

// divide result by number of millisecs in a day (rounded to a whole)
alert(Math.round(difference/86400000))
</script>

Open in new window

Use gettime() on your dates:

(date1.getTime() - date2.getTime() )/ (24*60*60*1000)

will give you the number of days between the dates

HTH,
Dan
Avatar of aviator21114
aviator21114

ASKER

GaryC123.... what's happening on lines 10 and 11 with the subscripts?  Date1(0) -1 can you define this construct?
Your months are in range 1-12 and JS needs them in the range 0-11.
ASKER CERTIFIED SOLUTION
Avatar of Gary
Gary
Flag of Ireland 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