Javascript - in a loop, adding within 1 week the malfunction object 6 months after correct

This Javascript generates a speaker list for every Sunday throughout the year. It starts on May 3, 2015 and is correct from November 1 to November 15. When a week is added to Nov 1 2015, it generates Nov 7 2015 instead of Nov 8 2015 (in Firefox, IE and Opera). What have I done wrong? The result looks like this: ... 25-Oct-2015 Delta (OK) 1-Nov-2015 Alpha (OK) 7-Nov-2015 Bravo (error - see Output)

<!DOCTYPE HTML>
<html>
<head>
<title>Speaker List Generator</title>
<meta charset="utf-8">

<script>
'use strict';
// Handy faux constants
var MINUTE = 60 * 1000;
var HOUR =   MINUTE * 60;
var DAY =    HOUR   * 24;
var WEEK =   DAY    *  7;

var month_str = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');

var speakers = new Array();
speakers[0]  = new Array();
speakers = [['Alpha','#FFFAAE'],['Bravo','#FFE3CD'],['Charlie','#AEFFB3'],['Delta','#D2FFFF'],['Echo','#EDEDED']];

// Initialize first date to May 3rd, 2015
var date_obj = new Date('May 3, 2015');
var d = date_obj.getDate();
var m = month_str[date_obj.getMonth()];
var y = date_obj.getFullYear();
var day = '';
</script>
</head>

<body style='font-family:courier'>

<h3>Speaker List</h3>
<table>
<tr>
  <th>Date</th><th>Speaker</th>
</tr>
<script>
// For each month
for (var j = 0; j < 8; j++) {
  // For each speaker
  for (var i = 0; i < speakers.length; i++) {
    // Echo only speaks on a 5th Sunday.
    // If Echo comes up, check for 1st Sunday.
    if ((speakers[i][0] == 'Echo') && (d < 8)) {
      continue;
    }
    // Add a space to 1 digit days
    day = (d < 10)?'&nbsp;'+d:d;
    document.writeln();
    document.writeln("  <tr>");
    document.writeln("    <td>"+day+"-"+m+"-"+y+"</td><td>"+speakers[i][0]+"</td>");
    document.writeln("  </tr>");

    // Add a week to the date for the next round.
    date_obj.setTime(date_obj.getTime() + WEEK);

    // Get next d, m, and y
    d = date_obj.getDate();
    m = month_str[date_obj.getMonth()];
    y = date_obj.getFullYear();
  }
}
</script>
</table>

</body>
</html>

      

+3


source to share


2 answers


The way you add the week won't work on daylight savings time, because you add exactly 24 hours, but some days have 23 hours and some have 25.

You can avoid this by setting the day instead. Change

date_obj.setTime(date_obj.getTime() + WEEK);

      



to

date_obj.setDate(date_obj.getDate() + 7);

      

Don't worry about postponing to next month, the property Date

will do it for you.

+5


source


This is because Daylight Saving Time ends November 1, 2015 ( http://www.timeanddate.com/time/change/usa/new-york?year=2015 ).

It's probably best to use a library like moment.js ( http://momentjs.com/ ) to take care of this for you.



var date = moment('20151101', 'YYYYMMDD')

date.calendar()
"11/01/2015"

date.add(7, 'days')

date.calendar()
"11/08/2015"

      

+1


source







All Articles