TigerTJJ
TigerTJJ

Reputation: 15

Date Code will only work in chrome

The problem is that this program will only work in Chrome, no matter what date format I use or when I parsed the dates using , it would return NaN.

The program converts the two dates (constant and a certain holiday) into milliseconds from Jan 1st, 1970. The dates are compared and subtracted. Then they are divided and rounded into seconds until the date. The problem, I believe lies when the dates are set. I do NOT want to mess with timezones.

jQuery in the answer is fine. Regex's are fine, but I don't understand them.

If the answer could have a working proof, that would be cool. Thanks!

The html is (all that matters)

<p id="output">

</p>

The code is

$(document).ready(function() {
  var date = new Date();
  var year = date.getFullYear();
  console.log(year + "-12-25");
  var christmasdate = new Date(year + "-12-24 24:00:00");
  $("#output").css("font-size","20px");
  $("#output").html("If this lasts more than a second, something is wrong.");
  setInterval(function() {
    date = new Date();
    var curr_time = date.getTime();
    var xmas_time = christmasdate.getTime();
    var time_left = Math.round((xmas_time - curr_time) / 1000);
    var output;
    if (time_left < 0) {
      output = "Christmas was " + Math.abs(time_left) + " seconds ago."
    }
    else {
      output = "There is " + time_left + " seconds until christmas eve.";
    }
    if (time_left == 1) {
      output = "There is " + time_left + "second until christmas eve.";
    }
    $("#output").html(output);
    var bodyheight = $(document).height();
    var allheight = $("body").height();
    $("h2").css("margin-top",(bodyheight / 2) - (allheight / 2))
  }, 1000);
});

The link is http://jsbin.com/suyedol/5/edit.

Upvotes: 0

Views: 43

Answers (2)

RobG
RobG

Reputation: 147373

Your computation of christmas in the current year seems overly complex and error prone. You certainly should not be using the Date constructor to parse strings (or Date.parse, they are equivalent for parsing).

Consider the following, which creates a date for 00:00:00 on Christmas morning in the current year.

var christmas = new Date();
christmas.setHours(0,0,0,0);
christmas.setMonth(11,25);

console.log(christmas.toString());

Upvotes: 2

Scott Hunter
Scott Hunter

Reputation: 49803

From MDN:

Because of the variances in parsing of date strings, it is recommended to always manually parse strings as results are inconsistent, especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone.

But instead of

var christmasdate = new Date(year + "-12-24 24:00:00");

You could instead use:

var christmasdate = new Date(year,11,24,24,0,0);

Which Safari computed as

Mon Dec 25 2017 00:00:00 GMT-0500 (EST)

Upvotes: 2

Related Questions