使用给定功能在JS中显示当前时间

时间:2019-04-01 20:18:20

标签: javascript time

需要使用给定功能在JS中显示当前时间。

Internet搜索显示JS使用Date()和Time()收集信息,但是运行HTML时日期和时间未显示在HTML中。

"use strict";
var $ = function(id) { return document.getElementById(id); };

var displayCurrentTime = function() {
    var now = new Date();  //use the 'now' variable in all calculations, etc.
    var Date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
    var hours = now.getHours()+ ":" + now.getMinutes() + ":" 
    + now.getSeconds();

    //Ok, problem now is getting HTML to call it up?
};

var padSingleDigit = function(num) {
    if (num < 10) { return "0" + num; }
    else { return num; }
};

window.onload = function() {
    // set initial clock display and then set interval timer to display
    // new time every second. Don't store timer object because it
    // won't be needed - clock will just run.

};

讲师的指示:

“请注意,要将计算机时间从24小时制转换为12小时制,请首先检查小时值是否大于12。如果是,则从小时值中减去12并设置AM / PM值更改为“ PM”。另外,请注意,午夜的小时值为0。

starter项目提供了四个函数:$函数,displayCurrentTime()函数的开始,padSingleDigit()函数(将前导零添加到单个数字)和onload事件处理程序的开始。

在displayCurrentTime()函数中,添加使用Date对象确定当前小时,分钟和秒的代码。将这些值转换为12小时制,确定AM / PM值,然后在适当的跨度标签中显示这些值。

然后,在onload事件处理程序中,编写一个计时器,该计时器每隔1秒调用一次displayCurrentTime()函数。另外,请确保页面加载后立即显示当前时间。 (一些注释已包含在入门代码中,以指导您放置东西的位置。”

1 个答案:

答案 0 :(得分:0)

要获取html元素,您首先需要一个。所以我做了一个ID为“时钟”的标签。然后,我设置一个间隔,每隔1000毫秒(1秒)运行一次,以给我正确的格式化时间。

clock = document.getElementById("clock");
let hours, minutes, seconds;

function checkDigits(num, hours) {
  if (num < 10) {
    return "0" + num
  } else {
    if (hours) {
      return num - 12
    }
    return num
  }
}

function updateTime() {
  date = new Date();
  hours = checkDigits(date.getHours(), true)
  minutes = checkDigits(date.getMinutes())
  seconds = checkDigits(date.getSeconds())
  clock.innerHTML = hours + ":" + minutes + ":" + seconds;
}

window.onload = function() {
  setInterval(function() {
    updateTime()
  }, 1000);
}
<h1 id="clock"></h1>

相关问题