在JavaScript中,可以使用Date
对象来获取当前系统时间。以下是一些基本的示例代码:
// 创建一个新的Date对象,默认为当前时间
var now = new Date();
// 输出当前日期和时间
console.log(now);
var now = new Date();
// 获取年份
var year = now.getFullYear();
// 获取月份(注意:月份从0开始计数,所以需要加1)
var month = now.getMonth() + 1;
// 获取日期
var date = now.getDate();
// 获取小时
var hours = now.getHours();
// 获取分钟
var minutes = now.getMinutes();
// 获取秒数
var seconds = now.getSeconds();
console.log(year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds);
function formatDate(date) {
var year = date.getFullYear();
var month = (date.getMonth() + 1).toString().padStart(2, '0');
var day = date.getDate().toString().padStart(2, '0');
var hours = date.getHours().toString().padStart(2, '0');
var minutes = date.getMinutes().toString().padStart(2, '0');
var seconds = date.getSeconds().toString().padStart(2, '0');
return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
}
var now = new Date();
console.log(formatDate(now));
var now = new Date();
var timestamp = now.getTime(); // 获取自1970年1月1日以来的毫秒数
console.log(timestamp);
Date
对象使得获取和处理日期和时间变得简单。Date
对象的月份是从0开始计数的,所以获取月份时需要加1。领取专属 10元无门槛券
手把手带您无忧上云