js封装参数当前时间秒数获取返回后的年月日时分秒的时间方法
以下是一个JavaScript函数,它接受一个时间戳作为参数,并返回该时间戳的年、月、日、小时、分钟和秒。
function getFormattedDate(timestamp) {
const date = new Date(timestamp * 1000);
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
const hours = ('0' + date.getHours()).slice(-2);
const minutes = ('0' + date.getMinutes()).slice(-2);
const seconds = ('0' + date.getSeconds()).slice(-2);
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
调用该函数时,您可以将当前时间戳作为参数传递,如下所示:
const now = Math.floor(Date.now() / 1000); // 当前时间戳,单位为秒
const formattedDate = getFormattedDate(now);
console.log(formattedDate); // 输出类似于 "2022-03-23 14:30:00" 的字符串
``
原文地址: https://www.cveoy.top/t/topic/fh7b 著作权归作者所有。请勿转载和采集!