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

如何在不使用Moment等库的情况下用JavaScript将ISO时间转为YYYYMMDDHHmmss格式?

在JavaScript中不依赖第三方库将ISO时间转换为YYYYMMDDHHmmss格式

根据你的需求,这里提供两种原生实现方案,按需选择:

方案一:字符串直接处理(推荐,匹配你的预期输出)

由于ISO格式的时间字符串结构非常规整,直接提取需要的数字部分是最可靠的方法,不会涉及时区转换导致的时间偏差。

const isoTime = '2023-08-07T09:38:43+07:00';
// 先截取时区标识(+/-)之前的部分,再移除所有非数字字符
const formattedTime = isoTime.split(/[+-]/)[0].replace(/\D/g, '');
console.log(formattedTime); // 输出:20230807093843

原理说明:

  1. split(/[+-]/)[0]:将字符串按+或-分割,取第一部分(即不带时区的时间部分:2023-08-07T09:38:43)
  2. replace(/\D/g, ''):移除所有非数字字符,直接得到连续的数字串

方案二:使用原生Date对象(适合时区转换场景)

如果你需要基于该ISO时间的时间戳,转换为本地时区或UTC时区的格式,可以用Date对象处理:

转换为UTC时区格式

const isoTime = '2023-08-07T09:38:43+07:00';
const date = new Date(isoTime);

const year = date.getUTCFullYear();
const month = String(date.getUTCMonth() + 1).padStart(2, '0'); // 月份从0开始,需加1并补零
const day = String(date.getUTCDate()).padStart(2, '0');
const hours = String(date.getUTCHours()).padStart(2, '0');
const minutes = String(date.getUTCMinutes()).padStart(2, '0');
const seconds = String(date.getUTCSeconds()).padStart(2, '0');

const formattedUTC = `${year}${month}${day}${hours}${minutes}${seconds}`;
console.log(formattedUTC); // 输出:20230807023843(对应UTC时间)

转换为本地时区格式

const isoTime = '2023-08-07T09:38:43+07:00';
const date = new Date(isoTime);

const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');

const formattedLocal = `${year}${month}${day}${hours}${minutes}${seconds}`;
console.log(formattedLocal); // 输出结果取决于你的本地时区

注意事项:

使用Date对象时,会自动将ISO时间转换为对应的时间戳,get*方法返回本地时区时间,getUTC*方法返回UTC时区时间,最终结果可能和原ISO字符串显示的时间不一致,需根据实际需求选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 14:28:35