JavaScript 获取当前系统时间 (yyyy-MM-dd hh:mm:ss 格式)
可以使用 JavaScript 的 'Date' 对象来获取当前系统时间,并使用 'getFullYear'、'getMonth'、'getDate'、'getHours'、'getMinutes' 和 'getSeconds' 方法来分别获取年、月、日、时、分和秒。然后使用字符串拼接的方式将它们组合在一起,形成所需的格式。
下面是一个示例代码:
function getCurrentTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
// 格式化月、日、时、分、秒,保证为两位数
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
hour = hour < 10 ? '0' + hour : hour;
minute = minute < 10 ? '0' + minute : minute;
second = second < 10 ? '0' + second : second;
var currentTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
return currentTime;
}
console.log(getCurrentTime()); // 输出当前系统时间的格式化字符串
运行以上代码,将会输出类似 '2022-01-01 12:34:56' 的格式化时间字符串。
原文地址: https://www.cveoy.top/t/topic/0wC 著作权归作者所有。请勿转载和采集!