javascript - JavaScript 获取时间函数
问题描述
我的 getTime 函数可以毫无问题地显示当前的小时、分钟和秒。我的问题是如何在不同的跨度上调用小时、分钟和秒?例子
<span id="hours" class="x"></span>
<span id="minutes" class="y"></span>
<span id="seconds" class="z"></span>
JavaScript 函数
<script language="JavaScript">
function getTime() {
const timeNow = new Date();
const hours = timeNow.getHours();
const minutes = timeNow.getMinutes();
const seconds = timeNow.getSeconds();
let timeString = '' + ((hours > 24) ? hours - 12 : hours);
timeString += ((minutes < 10) ? ":0" : ":") + minutes;
timeString += ((seconds < 10) ? ":0" : ":") + seconds;
timeString += (hours >= 12) ? "" : "";
//timeString += (hours >= 12) ? " P.M." : " A.M.";
return timeString;
}
const hoursSpan = document.getElementById('Hour');
setInterval(() => {
hoursSpan.textContent = getTime();
}, 1000);
</script>
解决方案
尝试这个。使变量成为全局变量以获得单独的小时分钟和秒值。您使用了错误的 id 来获取 span,并且该函数返回完整的字符串,因此仅将其拆分了几个小时
var timeNow = new Date();
var hours = timeNow.getHours();
var minutes = timeNow.getMinutes();
var seconds = timeNow.getSeconds();
function getTime() {
timeNow = new Date();
hours = timeNow.getHours();
minutes = timeNow.getMinutes();
seconds = timeNow.getSeconds();
let timeString = '' + ((hours > 24) ? hours - 12 : hours);
timeString += ((minutes < 10) ? ":0" : ":") + minutes;
timeString += ((seconds < 10) ? ":0" : ":") + seconds;
timeString += (hours >= 12) ? "" : "";
//timeString += (hours >= 12) ? " P.M." : " A.M.";
return timeString;
}
const hoursSpan = document.getElementById('hours');
const min = document.getElementById('minutes');
const sec = document.getElementById('seconds');
setInterval(() => {
hoursSpan.textContent = getTime().split(':')[0];
min.textContent=":"+minutes;
sec.textContent=":"+seconds;
}, 1000);
<span id="hours" class="x"></span>
<span id="minutes" class="y"></span>
<span id="seconds" class="z"></span>
推荐阅读
- json - 不能用 jq 返回第一个值
- iot - ATECC608A| 谷歌物联网核心 | 如何将 X 和 Y 整数 big-endian 格式转换为 base64 字符串有效的公钥格式?
- javascript - 开玩笑没有运行测试 - 加载配置时出错 - 您似乎正在使用本机 ECMAScript 模块配置文件
- sql - 将 Oracle 日期函数转换为 BigQuery
- dbt - 当版本从 0.18 更改为任何更高版本时,在 DBT 中运行快照的问题
- asp.net - openid 连接 AuthorizationCodeReceived 未触发
- sql - 如何在 PostgreSQL 中查询具有最高投票数且没有标志的值?
- reactjs - React native:从数组中删除一个项目
- c++ - 通过访问字符串数组创建一个返回星期几的函数
- html - css中的DOM解释,为什么html,body背景颜色属性的范围与body背景颜色属性不同