javascriptjqueryfunctionshow-hidegettime

Problematic IF statement with date and time comparisons in Javascript (getDay, Date, setHours, show, hide)


I am trying to make an auto-hide/show section for a webpage based on time and the day of the week. I want a section of HTML/CSS to automatically appear (after page load) every Saturday between 9:58am and 1:04pm. I believe the issue is with the Javascript section, particularly the IF statement. When I run the code, the HTML is shown (despite it currently being a Monday). I have done the obvious and changed the values for the IF comparisons, this isn't a case where the values for the comparisons are true. I'm an absolute novice with Javascript so any suggestions would be appreciated!

Javascript

$(document).ready(function liveplayertimer() { //Declare function, start on page load
  var d = new Date(); //d is date
  var n = d.getDay(); //n is day as int, 0 to 6 Sun to Sat
  var startTime = d.setHours(9, 57); //Sets start time for show to 09:57
  var endTime = d.setHours(13, 05); //Sets end time for show to 13:05

  if ((d.getTime() > startTime && d.getTime() < endTime) && n == 6) { //If within time AND on Saturday
    $('#rcdflivediv').show(); //Show the content
  }
  else { //Else
    $('#rcdflivediv').hide(); //Hide the content
  }
}) //End of function

HTML (incomplete, just a test placeholder for now)

<div id="rcdflivediv" style="display: none">
  <p>Live NOW! Listen in!</p>
  <a href=" link removed "> (Removed for now)
    <p>Listen live!</p>
  </a>
</div>

and CSS, just in case I've messed something up (incomplete, just a test placeholder for now)

#rcdflivediv {
  padding: 20px;
  font-family: Montserrat, sans-serif;
  size: 32px;
  background-color: #0077ff;
  color: #ffffff;
}

Solution

  • A Date object in JavaScript is mutable. So, if you want to get a different startTime, endTime and current date you need to make a different objects for it.

    var d = new Date(); //d is date
    var n = d.getDay(); //n is day as int, 0 to 6 Sun to Sat
    
    var startTime = new Date(); 
    startTime.setHours(9, 57);//Sets start time for show to 09:57
    
    var endTime = new Date();
    endTime.setHours(13, 05
    

    As Carsten has mentioned in a comment, you are modifying an original date by setHours.