JavaScript 中 new Date() 生成的日期格式转换为 ‘yyyy 您所在的位置:网站首页 JS日期格式化转换方法 JavaScript 中 new Date() 生成的日期格式转换为 ‘yyyy

JavaScript 中 new Date() 生成的日期格式转换为 ‘yyyy

2023-05-26 08:06| 来源: 网络整理| 查看: 265

JavaScript 中 new Date() 生成的日期格式转换为 ‘yyyy-MM-dd HH:mm:ss’ 格式的字符串

1、使用 Date 对象自带的方法 可以使用 Date 对象自带的方法来获取日期字符串的各个部分,然后将它们拼接成目标格式的字符串:

function formatDate(date) { 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 date = new Date(); const formattedDate = formatDate(date); console.log(formattedDate); // 输出类似 '2021-05-14 16:30:00' 的字符串

2、使用第三方库 也可以使用第三方库来格式化日期字符串,如 moment.js:

const moment = require('moment'); const date = new Date(); const formattedDate = moment(date).format('YYYY-MM-DD HH:mm:ss'); console.log(formattedDate); // 输出类似 '2021-05-14 16:30:00' 的字符串

或者使用 ES6 的模板字符串和 Date 对象自带的方法:

const date = new Date(); const formattedDate = `${date.getFullYear()}-${('0' + (date.getMonth() + 1)).slice(-2)}-${('0' + date.getDate()).slice(-2)} ${('0' + date.getHours()).slice(-2)}:${('0' + date.getMinutes()).slice(-2)}:${('0' + date.getSeconds()).slice(-2)}`; console.log(formattedDate); // 输出类似 '2021-05-14 16:30:00' 的字符串


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有