Solved

Javascript datediff function needed

Posted on 2007-06-03
4
4,114 Views
Last Modified: 2010-08-05
Hi everyone,

I need a javascript function to calculate the number of days between two dates in YYYYMMDD format.  Anyone have anything like this handy?

eg days = daysDiff('20070301','20061215');

Thanks!
0
Comment
Question by:quiTech
  • 2
  • 2
4 Comments
 
LVL 36

Expert Comment

by:Zyloch
ID: 19205145
function daysDiff(day1, day2) {
    var diff = Math.abs(Date.parse(day1) - Date.parse(day2));
    var daysDiff = Math.floor(diff / 1000 / 60 / 60 / 24);
    return daysDiff;
}

alert(daysDiff('2007/03/01', '2006/12/15'));
0
 

Author Comment

by:quiTech
ID: 19205222
Hi Zyloch,

That looks pretty good.  How would this work with a date that doesn't have the slashes (ie 20070301 instead of 2007/03/01).  Do I have to add the slashes or should it work without?  If I have to add them, how do I do that? (sorry my javascript skills are lacking severly ;-)

Thanks!
0
 
LVL 36

Accepted Solution

by:
Zyloch earned 500 total points
ID: 19205261
Try this:

function daysDiff(day1, day2) {
    day1 = addSlashes(day1);
    day2 = addSlashes(day2);
    var diff = Math.abs(Date.parse(day1) - Date.parse(day2));
    var daysDiff = Math.floor(diff / 1000 / 60 / 60 / 24);
    return daysDiff;
}

function addSlashes(day) {
    day = day.substring(0,4) + '/' + day.substr(4,2) + '/' + day.substr(6, 2);
    return day;
}

alert(daysDiff('20070301', '20061215'));
0
 

Author Comment

by:quiTech
ID: 19209533
WOW works perfectly!  Thanks so much!!!
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Batch, VBS, and scripts in general are incredibly useful for repetitive tasks.  Some tasks can take a while to complete and it can be annoying to check back only to discover that your script finished 5 minutes ago.  Some scripts may complete nearly …
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question