JavaScript日期格式化实现的三种常见方法
Date对象基础
基本使用方法
Date()是一个构造函数,必须使用new关键字来创建日期对象。
- 无参数时返回当前时间
- 有参数时返回指定时间
- 参数格式:
'2012-02-02 08:54:32' - 返回格式:
Thu Feb 02 2012 08:54:32 GMT+0800 (中国标准时间)
// 无参数示例
let currentDate = new Date();
console.log('当前时间', currentDate); // 当前时间 Sun May 28 2023 23:36:28 GMT+0800 (中国标准时间)
// 有参数示例
let specifiedDate = new Date('2012-02-02 08:54:32');
console.log('指定时间', specifiedDate); // 指定时间 Thu Feb 02 2012 08:54:32 GMT+0800 (中国标准时间)
常用API
Date对象提供了许多方法来获取日期和时间的各个部分,以下是一些常用方法:
let currentDate = new Date();
console.log(currentDate.getFullYear()); // 获取年份 2023
console.log(currentDate.getMonth() + 1); // 获取月份(注意:月份从0开始计数)
console.log(currentDate.getDate()); // 获取日期
console.log(currentDate.getDay()); // 获取星期几(注意:星期日返回0)
console.log(currentDate.getHours()); // 获取小时
console.log(currentDate.getMinutes()); // 获取分钟
console.log(currentDate.getSeconds()); // 获取秒数
日期格式化方法
方法一:使用toLocaleString
Date对象提供了toLocaleString方法,可以将日期和时间格式化为字符串。该方法有三个变体:
toLocaleString():返回日期和时间toLocaleDateString():返回日期toLocaleTimeString():返回时间
可选参数包括地区和时区信息:
let currentTime = new Date();
console.log(currentTime.toLocaleString()); // 示例输出:2023/5/28 23:36:28
console.log(currentTime.toLocaleDateString()); // 示例输出:2023/5/28
console.log(currentTime.toLocaleTimeString()); // 示例输出:23:36:28
console.log(currentTime.toLocaleString('en-US', { timeZone: 'America/New_York' })); // 示例输出:5/28/2023, 11:08:39 AM
方法二:使用字符串操作
通过字符串操作可以实现高度自定义的日期格式。padStart方法用于在字符串左侧填充字符,确保两位数显示:
let currentTime = new Date();
console.log(currentTime.getFullYear().toString().padStart(4, '0')); // 示例输出:2023
console.log((currentTime.getMonth() + 1).toString().padStart(2, '0')); // 示例输出:05
console.log(currentTime.getDate().toString().padStart(2, '0')); // 示例输出:29
console.log('星期' + (currentTime.getDay() === 0 ? 7 : currentTime.getDay())); // 示例输出:星期1
console.log(currentTime.getHours().toString().padStart(2, '0')); // 示例输出:01
console.log(currentTime.getMinutes().toString().padStart(2, '0')); // 示例输出:19
console.log(currentTime.getSeconds().toString().padStart(2, '0')); // 示例输出:55
方法三:封装格式化函数
let currentTime = new Date();
function formatDateTime(timer) {
const year = timer.getFullYear();
const month = timer.getMonth() + 1;
const day = timer.getDate();
const hour = timer.getHours();
const minute = timer.getMinutes();
const second = timer.getSeconds();
return `${pad(year, 4)}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(minute)}:${pad(second)}`;
}
function pad(value, total = 2, filler = '0') {
return value.toString().padStart(total, filler);
}
console.log(formatDateTime(currentTime)); // 示例输出:2023-05-29 00:30:19
方法四:使用第三方库(Moment.js)
Moment.js是一个流行的日期处理库,提供丰富的功能和简便的API。
- 安装:
npm install moment
- 引入:
import moment from 'moment';
Vue.prototype.$moment = moment;
- 使用:
console.log(this.$moment().format('YYYY-MM-DD HH:mm:ss')); // 示例输出:2023-05-29 00:30:19
时间戳处理
Date对象可以获取当前时间的时间戳(从1970年1月1日至今的毫秒数):
let currentDate = new Date();
console.log(currentDate.valueOf()); // 示例输出:当前时间戳
console.log(currentDate.getTime());
console.log(+new Date()); // 简写形式
console.log(Date.now()); // ES6新增方法,部分旧浏览器不支持
倒计时函数示例
function countdownTimer(targetTime) {
const currentTime = +new Date();
const targetTimestamp = +new Date(targetTime);
const timeDifference = (targetTimestamp - currentTime) / 1000;
const seconds = pad(Math.floor(timeDifference % 60));
const minutes = pad(Math.floor(timeDifference / 60 % 60));
const hours = pad(Math.floor(timeDifference / 60 / 60 % 24));
const days = pad(Math.floor(timeDifference / 60 / 60 / 24));
return `${days}天${hours}小时${minutes}分钟${seconds}秒`;
}
function pad(value, total = 2, filler = '0') {
return value.toString().padStart(total, filler);
}
console.log(countdownTimer('2122-05-19 08:00:00')); // 示例输出:1000天00小时00分钟00秒