JS 格式化日期

在前端开发中,我们经常需要对日期进行格式化,以便展示给用户或者发送给后端。JavaScript提供了一些内置的方法来格式化日期,本文将介绍如何在JavaScript中格式化日期。
使用内置Date对象
JavaScript中的Date对象用于处理日期和时间。我们可以使用Date对象的方法来获取当前日期时间,并对其进行格式化。
获取当前日期时间
要获取当前日期时间,我们可以直接实例化一个Date对象,它会自动获取当前的日期时间。
const now = new Date();
console.log(now); // 输出当前日期时间
运行上面的代码,会输出类似以下格式的当前日期时间:
Sun Oct 17 2021 14:23:42 GMT+0800 (中国标准时间)
格式化日期
要格式化日期,我们可以使用Date对象的方法,例如getDate()、getMonth()、getFullYear()等方法来获取年、月、日等信息,然后拼接成我们想要的格式。
下面是一个示例,将当前日期时间格式化为yyyy-mm-dd的格式:
const now = new Date();
const year = now.getFullYear();
const month = (now.getMonth() + 1).toString().padStart(2, '0');
const date = now.getDate().toString().padStart(2, '0');
const formattedDate = `{year}-{month}-${date}`;
console.log(formattedDate);
运行上面的代码,会输出当前日期的yyyy-mm-dd格式:
2021-10-17
格式化时间
类似地,我们也可以将时间部分格式化为我们想要的格式。例如,将当前时间格式化为hh:mm:ss的格式:
const now = new Date();
const hours = now.getHours().toString().padStart(2, '0');
const minutes = now.getMinutes().toString().padStart(2, '0');
const seconds = now.getSeconds().toString().padStart(2, '0');
const formattedTime = `{hours}:{minutes}:${seconds}`;
console.log(formattedTime);
运行上面的代码,会输出当前时间的hh:mm:ss格式:
14:23:42
完整格式化
除了单独格式化日期和时间,我们还可以将日期时间整合起来,格式化为一个完整的格式,例如yyyy-mm-dd hh:mm:ss:
const now = new Date();
const year = now.getFullYear();
const month = (now.getMonth() + 1).toString().padStart(2, '0');
const date = now.getDate().toString().padStart(2, '0');
const hours = now.getHours().toString().padStart(2, '0');
const minutes = now.getMinutes().toString().padStart(2, '0');
const seconds = now.getSeconds().toString().padStart(2, '0');
const formattedDateTime = `{year}-{month}-{date}{hours}:{minutes}:{seconds}`;
console.log(formattedDateTime);
运行上面的代码,会输出当前日期时间的yyyy-mm-dd hh:mm:ss格式:
2021-10-17 14:23:42
使用第三方库
除了手动拼接日期时间的方式,我们还可以使用一些第三方库来更方便地格式化日期。例如,moment.js是一个常用的JavaScript日期库,提供了丰富的日期时间处理功能。
使用moment.js
首先,我们需要引入moment.js库,可以通过CDN引入,也可以通过npm安装引入:
<script src="https://cdn.jsdelivr.net/npm/moment/min/moment.min.js"></script>
或者
npm install moment --save
然后,我们可以使用moment.js来格式化日期时间。例如,将当前日期时间格式化为yyyy-mm-dd hh:mm:ss的格式:
const now = moment();
const formattedDateTime = now.format('YYYY-MM-DD HH:mm:ss');
console.log(formattedDateTime);
运行上面的代码,会输出当前日期时间的yyyy-mm-dd hh:mm:ss格式:
2021-10-17 14:23:42
moment.js还提供了许多其他格式化选项和功能,可以根据实际需求进行进一步的调整和处理。
总结
本文介绍了如何在JavaScript中格式化日期。通过内置的Date对象和第三方库moment.js,我们可以方便地处理和格式化日期时间,满足不同的需求。在实际开发中,选择合适的方式来格式化日期,可以提高开发效率和用户体验。
极客笔记