Solved

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

Posted on 2013-09-22
Medium Priority
297 Views
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,
0
Question by:aviator21114
• 2
• 2

LVL 58

Expert Comment

ID: 39513244
``````<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)
</script>
``````
0

LVL 35

Expert Comment

ID: 39513246

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

will give you the number of days between the dates

HTH,
Dan
0

Author Comment

ID: 39513260
GaryC123.... what's happening on lines 10 and 11 with the subscripts?  Date1(0) -1 can you define this construct?
0

LVL 35

Expert Comment

ID: 39513268
Your months are in range 1-12 and JS needs them in the range 0-11.
0

LVL 58

Accepted Solution

Gary earned 2000 total points
ID: 39513271
It's building the date as a date object 2013,11,01 - this is how js will understand it.

The 11 is not a mistake - months in js start from 0 to 11
0

## Featured Post

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.