javascript 如何将包含时间偏移量的日期字符串转换为其他格式?[duplicate]

sz81bmfz  于 2023-03-06  发布在  Java
关注(0)|答案(1)|浏览(117)
    • 此问题在此处已有答案**:

How do I format a date in JavaScript?(68个答案)
2天前关闭。
我收到了日期为"2020 - 09 - 09T12:41:41 -04:00"的字符串。这个字符串似乎包含时间偏移。我需要将其转换为"3/15/2020,1:23:09 PM"格式。我该如何实现呢?
我试图用该字符串创建新的日期对象,但它显示无效的日期。

nbnkbykc

nbnkbykc1#

删除非法空格后,可以使用INTL DateTime format

const d = new Date("2020-09-09T12:41:41-04:00")
console.log(d)

const options = {
  year: "numeric",
  month: "numeric",
  day: "numeric",
  hour : "numeric",
  minute : "numeric",
  second : "numeric",
};
const dateString = new Intl.DateTimeFormat("en-US", options).format(d);
console.log(dateString);

或者完全控制

const toAMPM = hhmmss => {
  const [hours, minutes, seconds] = hhmmss.split(":");
  const formatHours = hours % 12 || 12;
  const ampm = hours < 12 ? "AM" : "PM";
  return `${+formatHours}:${minutes}:${seconds} ${ampm}`;
};
const convertTime = dateString => {
  const d = new Date(dateString).toISOString();
  const [_, yyyy, mm, dd, time] = d.match(/(\d{4})-(\d{2})-(\d{2})T(\d{2}:\d{2}:\d{2})\./);
  return `${+mm}/${+dd}/${yyyy}, ${toAMPM(time)}`;
};

console.log(convertTime("2023-02-28T12:41:41-04:00"));

相关问题