You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用DateFormatter将日期及Date.now转换为字符串?

不借助DateFormatter转换日期为字符串的方法

一、处理普通Date实例(比如new Date()生成的日期)

直接利用Date对象的原生方法获取年、月、日、时、分、秒等部分,手动拼接成你需要的格式。注意月份从0开始计数,需要加1后再处理。

示例代码(生成YYYY-MM-DD HH:mm:ss格式):

const date = new Date();
// 补零函数,兼容低版本环境
const padZero = num => num < 10 ? `0${num}` : num;

const year = date.getFullYear();
const month = padZero(date.getMonth() + 1);
const day = padZero(date.getDate());
const hours = padZero(date.getHours());
const minutes = padZero(date.getMinutes());
const seconds = padZero(date.getSeconds());

// 拼接成目标格式
const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
console.log(formattedDate); // 输出示例:"2024-05-20 15:42:30"

如果不需要自定义格式,也可以直接用Date实例的原生toString方法快速转换:

  • date.toString():返回带时区的完整字符串,如"Mon May 20 2024 15:42:30 GMT+0800 (中国标准时间)"
  • date.toLocaleString():返回本地化格式的日期时间,如"2024/5/20 15:42:30"
  • date.toDateString():仅返回日期部分,如"Mon May 20 2024"
  • date.toTimeString():仅返回时间部分,如"15:42:30 GMT+0800 (中国标准时间)"

二、处理Date.now()生成的时间戳

Date.now()返回的是毫秒级时间戳,需要先将其转换为Date实例,再复用上面的方法:

示例代码:

const timestamp = Date.now();
const dateFromTs = new Date(timestamp);
const padZero = num => num < 10 ? `0${num}` : num;

const year = dateFromTs.getFullYear();
const month = padZero(dateFromTs.getMonth() + 1);
const day = padZero(dateFromTs.getDate());
const hours = padZero(dateFromTs.getHours());
const minutes = padZero(dateFromTs.getMinutes());
const seconds = padZero(dateFromTs.getSeconds());

const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
console.log(formattedDate);

内容的提问来源于stack exchange,提问作者Legion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 04:35:29