Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Javascript datediff function needed

Posted on 2007-06-03
4
Medium Priority
?
4,146 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 2000 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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

In threads here at EE, each comment has a unique Identifier (ID). It is easy to get the full path for an ID via the right-click context menu. However, we often want to post a short link within a thread rather than the full link. This article shows a…
In this blog, we’ll look at how improvements to Percona XtraDB Cluster improved IST performance.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
Suggested Courses

972 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