0

Funny thing is happening when trying to subtract a day off the current date in JavaScript.

Here is what is going on:

var d = new Date($(".nav-tabs li").first().find('.specific-date').text());
d = new Date(d.getTime() - (24*60*60*1000));

d is set from a JQuery button click. Date examples going in would be, 04/7/2015. Subtract that time by milliseconds. For example, lets say I log todays current date subtracted by one day.

Mon Apr 06 2015 00:00:00 GMT-0500 (CDT) is my output which is correct.

Now when I implement this into a slide bar that you are able to go up a date and down a date, this is what goes on.

$(".nav-tabs li").last().remove();
if(d.getDay() == 0)
{
    $(".arrow-left").after('<li role="presentation"><a href="#">
<span class="specific-day">'+weekday[6]+'</span><br/>
<span class="specific-date">' + d.getMonth() + '/' + d.getDate() + '/' +  d.getFullYear()+'
</span></a></li>');
}
else
{
    $(".arrow-left").after('<li role="presentation"><a href="#">
<span class="specific-day">'+weekday[d.getDay() - 1]+'
</span><br/><span class="specific-date">' + d.getMonth() + '/' + d.getDate() + '/' +  d.getFullYear()+'
</span></a></li>');
}

weekday is an array that contains abbreviations of the current day.

Here is how this is declared.

var weekday = new Array(7);
    weekday[0]=  "Mon";
    weekday[1] = "Tue";
    weekday[2] = "Wed";
    weekday[3] = "Thu";
    weekday[4] = "Fri";
    weekday[5] = "Sat";
    weekday[6] = "Sun";

Now my issue running into this is, the month each time the date is subtracted by one day is also subtracted by one month.

Example:

Mon Apr 06 2015 00:00:00 GMT-0500 (CDT) becomes Mon Mar 06 2015 00:00:00 GMT-0500 (CDT) on the last section where JQuery implements the new results.

Suggestions?

David Biga
  • 2,763
  • 8
  • 38
  • 61

1 Answers1

0

I ended up moving to moment.js it provides a phenomenal library and ease of use with great functions.

Here is what I did:

var d = moment($(".nav-tabs li").first().find('.specific-date').text());
d = d.subtract(1, 'days') ;// 1
$(".nav-tabs li").last().remove();
$(".arrow-left").after('<li role="presentation"><a href="#"><span class="specific-day">'+d.format("ddd")+'</span><br/><span class="specific-date">' + d.format("MM") + '/' + d.format("DD") + '/' +  d.format("YYYY")+'</span></a></li>');

Eliminated many lines.

David Biga
  • 2,763
  • 8
  • 38
  • 61