首页 > 信息 > 科技资讯 >

🌟JS日期格式化技巧✨

发布时间:2025-04-08 15:11:28来源:

在日常开发中,日期格式化是常见的需求,如何优雅地处理呢?以下分享几个实用技巧!💬

首先,利用`Date`对象获取基础时间信息。例如:

```javascript

const now = new Date();

console.log(now.getFullYear()); // 获取年份

console.log(now.getMonth() + 1); // 获取月份(注意:getMonth从0开始)

```

其次,借助`toLocaleDateString`进行本地化格式化,简单又高效:

```javascript

const options = { year: 'numeric', month: 'long', day: 'numeric' };

console.log(new Date().toLocaleDateString('zh-CN', options));

// 输出:2023年10月5日

```

如果需要更复杂的格式,推荐使用`Intl.DateTimeFormat`:

```javascript

const formatter = new Intl.DateTimeFormat('zh-CN', {

year: 'numeric',

month: '2-digit',

day: '2-digit',

hour: '2-digit',

minute: '2-digit',

second: '2-digit'

});

console.log(formatter.format(new Date()));

// 输出类似:2023-10-05 14:23:45

```

掌握这些技巧,让你的代码更加简洁且功能强大!🚀

免责声明:本答案或内容为用户上传,不代表本网观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。 如遇侵权请及时联系本站删除。