在JavaScript中处理日期格式化是开发中的常见需求,本文将详细介绍5种实用方法,并提供可直接复制的代码示例。
const date = new Date(); // 获取基本日期组件 const year = date.getFullYear(); // 2024 const month = date.getMonth() + 1; // 7(注意月份从0开始) const day = date.getDate(); // 25 const hours = date.getHours(); // 14 const minutes = date.getMinutes(); // 30 // 基础拼接格式 const basicFormat = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`; // 输出:2024-07-25
function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') { const pad = (n) => n.toString().padStart(2, '0'); return format .replace(/YYYY/g, date.getFullYear()) .replace(/MM/g, pad(date.getMonth() + 1)) .replace(/DD/g, pad(date.getDate())) .replace(/HH/g, pad(date.getHours())) .replace(/mm/g, pad(date.getMinutes())) .replace(/ss/g, pad(date.getSeconds())); } // 使用示例 const now = new Date(); console.log(formatDate(now)); // 2024-07-25 14:30:45 console.log(formatDate(now, 'YYYY年MM月DD日')); // 2024年07月25日
const date = new Date(); // 日期格式 console.log( new Intl.DateTimeFormat('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(date) ); // 2024/07/25 // 完整日期时间 console.log( new Intl.DateTimeFormat('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }).format(date) ); // 2024/07/25 14:30:45
moment.js(传统方案)
moment().format('YYYY-MM-DD HH:mm:ss'); // 2024-07-25 14:30:45
date-fns(现代轻量方案)
import { format } from 'date-fns';
format(new Date(), ‘yyyy-MM-dd HH:mm:ss’); // 2024-07-25 14:30:45
### 五、模板扩展方案
```javascript
Date.prototype.format = function(pattern = 'YYYY-MM-DD') {
const pad = n => n.toString().padStart(2, '0');
return pattern
.replace('YYYY', this.getFullYear())
.replace('MM', pad(this.getMonth() + 1))
.replace('DD', pad(this.getDate()))
.replace('HH', pad(this.getHours()))
.replace('mm', pad(this.getMinutes()))
.replace('ss', pad(this.getSeconds()));
};
// 使用示例
new Date().format('YYYY/MM/DD HH:mm'); // 2024/07/25 14:30
注意事项:
参考资料:
通过上述方法,开发者可以根据项目需求灵活选择最适合的日期格式化方案,简单项目推荐自定义函数,复杂场景建议使用date-fns等现代库,既能保证功能完善,又有利于代码维护。