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

如何将PostgreSQL返回的GMT日期转为09/12/24格式?

解决方法

问题出在时区转换:你拿到的日期是GMT(UTC)时间的00:00,moment默认会用本地时区解析,如果你所在时区比UTC晚(比如西半球时区),00:00 UTC就会变成前一天的本地时间,导致显示错误。

最简单的处理方式有两种:

1. 用moment.js的UTC模式解析

直接使用moment.utc()来解析原始日期字符串,这样就会忽略本地时区,直接基于UTC处理日期:

const originalDate = 'Thu, 12 Sep 2024 00:00:00 GMT';
const formattedDate = moment.utc(originalDate).format('MM/DD/YY');
console.log(formattedDate); // 输出: 09/12/24

2. 用原生JavaScript(无需moment.js)

如果不想依赖moment,用原生Intl.DateTimeFormat也能轻松实现,同样指定UTC时区:

const originalDate = 'Thu, 12 Sep 2024 00:00:00 GMT';
const date = new Date(originalDate);
const formattedDate = new Intl.DateTimeFormat('en-US', {
  timeZone: 'UTC',
  month: '2-digit',
  day: '2-digit',
  year: '2-digit'
}).format(date);
console.log(formattedDate); // 输出: 09/12/24

两种方法都能避免时区转换带来的日期偏移,直接得到你想要的MM/DD/YY格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 13:07:04