ebkod ebkod - 3 years ago 101
Javascript Question

Why does the date not adjust to the time set by UTC?

When printing the time for the clocks, a similar code works and adjusts for the timezone selected, but this does not work for printing the date. Any idea why?

It just displays the UTC default time.

<script>
function cetDT(){

var now = new Date();
var today = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());

var day = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();

var anHour = 1000 * 60 * 60;
today = new Date(today.getTime() - anHour * -2);

var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();

if (hours >= 12){
meridiem = "";
}
else {
meridiem = "";
}


if (minutes<10){
minutes = "0" + minutes;
}
else {
minutes = minutes;
}

if (seconds<10){
seconds = "0" + seconds;
}
else {
seconds = seconds;
}

document.getElementById("cetDT").innerHTML = (day + '/' + (parseFloat (month) + 1) + '/' + year);

}

cetDT();
</script>

Answer Source

You're using now.getUTCDate(), now.getUTCHours() and similar, which will grab the current date and time in UTC.

To get the local equivalent, you're looking for now.getDate(), now.getHours() etc. Note the lack of 'UTC' in the names.

Note that even though you're updating the today variable with today = new Date(today.getTime() - anHour * -2), today is initialed earlier with the UTC times. Thus, getTime() will be relative to UTC.

To resolve this, all you need to do is swap out the UTC times:

function cetDT() {

  var now = new Date();
  var today = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds());

  var day = today.getDate();
  var month = today.getMonth();
  var year = today.getFullYear();

  var anHour = 1000 * 60 * 60;
  today = new Date(today.getTime() - anHour * -2);

  var hours = today.getHours();
  var minutes = today.getMinutes();
  var seconds = today.getSeconds();

  if (hours >= 12) {
    meridiem = "";
  } else {
    meridiem = "";
  }


  if (minutes < 10) {
    minutes = "0" + minutes;
  } else {
    minutes = minutes;
  }

  if (seconds < 10) {
    seconds = "0" + seconds;
  } else {
    seconds = seconds;
  }

  document.getElementById("cetDT").innerHTML = (day + '/' + (parseFloat(month) + 1) + '/' + year);

}

cetDT();

Note that there's also several bits of code that are completely redundant, such as else { seconds = seconds; }. You may wish to look into refactoring this code ;)

Hope this helps! :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download