gx2g
gx2g

Reputation: 311

how many days left for birthday from today

I have an JavaScript array here. I need to compare the birthday value with a set date and update the record with a new key value.

var employees = [
    {
        "internalid":"1", 
        "name":"Abe Anderson", 
        "email":"[email protected]", 
        "birthdate":"9/25/1974", 
        "supervisor":"3", 
        "2012 Revenue":"100000.00", 
        "2013 Revenue":"0.00"
    }
];

I wrote this here which works great,

for (var i = 0; i < employees.length; i++) {
    var cDate = new Date("2014/01/01");
    var newDate = cDate.getMonth()+1 + '/' + cDate.getDate() + '/' + cDate.getFullYear();
    var eBday = employees[i].birthdate;
}

I'm having a hard time writing the math to compare the two dates correctly. Can anyone help me? I need to calculate how many days left each person has until his or her birthday and update the JavaScript array. I'm stuck!

Upvotes: 2

Views: 859

Answers (2)

codeandcloud
codeandcloud

Reputation: 55210

Try this.

var employees = [{
  "internalid": "1",
  "name": "Abe Anderson",
  "email": "[email protected]",
  "birthdate": "9/25/1974",
  "supervisor": "3",
  "2012 Revenue": "100000.00",
  "2013 Revenue": "0.00"
}];

for (var i = 0; i < employees.length; i++) {
  employees[i].daysToBirthday = DaysToBirthdayFromToday(employees[i].birthdate);
}

console.log(employees);


function DaysToBirthdayFromToday(birthdayString) {
  "use strict";
  var currentYear = new Date().getFullYear();
  //get today midnight
  var today = new Date(currentYear, new Date().getMonth(), new Date().getDate());
  var birthdayParts = birthdayString.split("/");
  var yearBirthday = new Date(currentYear, birthdayParts[0] - 1, birthdayParts[1]);
  var timDiffInMilliSeconds = yearBirthday.getTime() - today.getTime();
  var timDiffInDays = timDiffInMilliSeconds / (1000 * 60 * 60 * 24);
  return timDiffInDays < 0 ? 0 : timDiffInDays; // set zero if past
}

Upvotes: 0

user6624456
user6624456

Reputation:

I'd recommend using momentJS. its the go to library for javascript dates handling.

in momentJS you can use moment.diff method: http://momentjs.com/docs/#/displaying/difference/

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

This guy answered how to make compare using momentJS in details:https://stackoverflow.com/a/22601120/6624456

Upvotes: 1

Related Questions