最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to get difference in year where dates are in yyyy-mm-dd? - Stack Overflow

programmeradmin2浏览0评论

i want to get the difference between two dates which are give in yyyy-mm-dd format difference should be in year.

        var ds='2002-09-23';
        var today_date = new Date();
        alert(today_date);
        Date.prototype.yyyymmdd = function() {
        var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
        var dd  = this.getDate().toString();
        var dt = yyyy +"-"+(mm[1]?mm:"0"+mm[0]) +"-"+ (dd[1]?dd:"0"+dd[0]);// padding
        var num_years = diff_date/31536000000;
        alert(num_years);
        if (num_years>18){
           alert (num_years);
        }else{
        alert ("i m not 18");
               }

please help me out.

i want to get the difference between two dates which are give in yyyy-mm-dd format difference should be in year.

        var ds='2002-09-23';
        var today_date = new Date();
        alert(today_date);
        Date.prototype.yyyymmdd = function() {
        var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
        var dd  = this.getDate().toString();
        var dt = yyyy +"-"+(mm[1]?mm:"0"+mm[0]) +"-"+ (dd[1]?dd:"0"+dd[0]);// padding
        var num_years = diff_date/31536000000;
        alert(num_years);
        if (num_years>18){
           alert (num_years);
        }else{
        alert ("i m not 18");
               }

please help me out.

Share Improve this question asked Jul 5, 2012 at 14:08 Manish MalviyaManish Malviya 8712 gold badges13 silver badges19 bronze badges 1
  • So, for '2011-12-31' and '2012-01-01' it should return 1 (year)? – Šime Vidas Commented Jul 5, 2012 at 14:33
Add a comment  | 

8 Answers 8

Reset to default 10

This is much shorter:

var yearsApart = new Date(new Date - new Date('2002-09-23')).getFullYear()-1970

… but be careful to take care of non UTC time zones by providing the correct datetime string!

You need no library for this, just pure javascript:

function wholeYearsBetweenTwoDates(dateOneString, dateTwoString) {
    // assuming that dateTwo is later in time than dateOne
    var dateOne = getDateFromString(dateOneString);
    var dateTwo = getDateFromString(dateTwoString);

    var result = dateTwo.getFullYear() - dateOne.getFullYear();

    dateOne.setFullYear(dateTwo.getFullYear());
    if (dateOne > dateTwo) {
        // compensate for the case when last year is not full - e.g., when
        // provided with '2009-10-10' and '2010-10-09', this will return 0
        result -= 1;
    }

    return result;
}

function getDateFromString(stringDate) {
    var dateParts = stringDate.split('-');
    var result = new Date(dateParts[0], dateParts[1], dateParts[2]);
    return result;
}

Try the following code to get the difference in years...

function getDateDiffInYears(date1, date2) {
  var dateParts1 = date1.split('-')
    , dateParts2 = date2.split('-')
    , d1 = new Date(dateParts1[0], dateParts1[1]-1, dateParts1[2])
    , d2 = new Date(dateParts2[0], dateParts2[1]-1, dateParts2[2])

  return new Date(d2 - d1).getYear() - new Date(0).getYear() + 1;
}

var diff = getDateDiffInYears('2005-09-23', '2012-07-3');

console.log(diff); // => 7 years

Good luck!

I had been using the formula var yearsApart=milli/milliPerYear but when the day and the month are the same the rounded value is not correct.

Here you have the script I'm using right now ...

function yearDifferenceDates(firstDateDay, firstDateMonth, firstDateYear, secondDateDay, secondDateMonth, secondDateYear) {

    var fisrtDate   = new Date(firstDateYear, firstDateMonth - 1, firstDateDay);
    var secondDate  = new Date(secondDateYear, secondDateMonth - 1, secondDateDay);

    if(firstDateDay == secondDateDay && (firstDateMonth - 1) == (secondDateMonth - 1)) {
        return Math.round((secondDate-fisrtDate)/(1000*60*60*24*365.242199));
    }

    return Math.floor((secondDate-fisrtDate)/(1000*60*60*24*365.242199));
}

First you have to pick a JavaScript library for parsing dates using a format string (so you can provide date in the format you prefer). Try this great library (at least you do not have to care about implementation details. Date constructor and Date.parse methods must match but it's not mandatory they can parse a simple date in that format).

var date1 = getDateFromFormat("1999-10-10", "YYYY-MM-DD");
var date2 = getDateFromFormat("2012-10-10", "YYYY-MM-DD");

Then, when you have to calculate the difference:

var millisecondsPerSecond = 1000;
var millisecondsPerMinute = millisecondsPerSecond * 60;
var millisecondsPerHour = millisecondsPerMinute * 60;
var millisecondsPerDay = millisecondsPerHour * 24;
var millisecondsPerYear = millisecondsPerDay * 365.26;

var years = Math.round((date2 - date1) / millisecondsPerYear);

If you need a raw calculation you can use getFullYear() directly.

You can compare dates more easily if you convert them to their millisecond values.

var birthday = new Date('2002-09-23');
var now = new Date();
var age = now.getTime() - birthday.getTime();

if (age < (1000 * 60 * 60 * 24 * 365 * 18)) { // number of milliseconds in 18 years
   document.write('not over 18');
} else {
  document.write('over 18');
}

Above has a little bug but this work :)

NOT WORKING:   var millisecondsPerHour = millisecondsPerMinute = 60;
WORKING FINE:  var millisecondsPerHour = millisecondsPerMinute * 60;

But thx Adriano Repetti

Here the complete code (with dot Format)

var date1 = "01.01.2014";
var date2 = "31.12.2016";

var date1 = date1.split(".");
var date2 = date2.split(".");

date1 = String(date1[2] +"-"+ date1[1] +"-"+ date1[0]);
date2 = String(date2[2] +"-"+ date2[1] +"-"+ date2[0]);

var date1 = Date.parse(date1);
var date2 = Date.parse(date2);


//(Not for Europa :) )
//var date1 = Date.parse("2014-01-01");
//var date2 = Date.parse("2016-12-31");

var millisecondsPerSecond = 1000;
var millisecondsPerMinute = millisecondsPerSecond * 60;
var millisecondsPerHour = millisecondsPerMinute * 60;
var millisecondsPerDay = millisecondsPerHour * 24;
var millisecondsPerYear = millisecondsPerDay * 365.26;

// IN YEARS
var years = (date2 - date1) / millisecondsPerYear;

// IN MONTHS
var month = years * 12 // Very tricky, I know ;)
var d1=new Date(2002, 9, 23);
var d2=new Date();

var milli=d2-d1;
var milliPerYear=1000*60*60*24*365.26;

var yearsApart=milli/milliPerYear;

console.log(yearsApart)
发布评论

评论列表(0)

  1. 暂无评论