1

Title pretty much says it, my script for how many weeks ago from a date is not accounting for the year, and returning a bad value?

var today = new Date();
var timestamp = new Date($(this).attr('timestamp') * 1000);

Date.prototype.getWeeks = function()
{
    var jan = new Date(this.getFullYear(), 0, 1);
    var now = new Date(this.getFullYear(),this.getMonth(),this.getDate());
    var doy = ((now - jan + 1) / 86400000);
    return Math.ceil(doy / 7)
};

console.log('Today: ' + today);                 // Date {Thu Oct 31 2013 09:21:19 GMT-0700 (PDT)}
console.log('PastT: ' + timestamp);             // Date {Fri Nov 20 2009 17:00:00 GMT-0800 (PST)}

console.log('Today: ' + today.getWeeks());      // 44 <-- Should be zero
console.log('PastT: ' + timestamp.getWeeks());  // 47 <-- Not accounting for the Years

console.log('Since: ' + (today.getWeeks() - timestamp.getWeeks())); // time ago = -3
charlietfl
  • 170,828
  • 13
  • 121
  • 150
ehime
  • 8,025
  • 14
  • 51
  • 110

1 Answers1

2

You could compare the dates then convert the difference (in milliseconds) to weeks:

function dateDiffInWeeks(a,b) {
    var _MS_PER_WEEK = 1000 * 60 * 60 * 24 * 7;
    var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
    var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
    return Math.floor((utc2 - utc1) / _MS_PER_WEEK);
}

var today = new Date();
var anotherDay = new Date("Fri Nov 20 2009");

alert(dateDiffInWeeks(today,anotherDay));

JSFiddle

Disclosure: This is HEAVILY based on this SO answer.

Community
  • 1
  • 1
Moob
  • 14,420
  • 1
  • 34
  • 47