如何将包含时间偏移的日期字符串转换为另一种格式?

huangapple go评论79阅读模式
英文:

How to convert date string which contains time offset to another format?

问题

我收到了这样的字符串作为日期 "2020-09-09T12:41:41 -04:00"。看起来这个字符串包含时间偏移。我需要将它转换成 "3/15/2020, 1:23:09 PM" 的格式。我该如何实现这个目标?

我尝试使用这个字符串创建一个新的日期对象,但它显示 "无效日期"。

英文:

I'm receiving this kind of string as date "2020-09-09T12:41:41 -04:00".
It seems like this string contains time offset.
I need to convert this to "3/15/2020, 1:23:09 PM " format.
How can I achieve this?

I tried to create new Date object with that string but it shows me Invalid Date.

答案1

得分: 1

你可以在移除非法空格后使用INTL DateTime格式

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"));
英文:

You can use INTL DateTime format after you remove the illegal space

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

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

<!-- end snippet -->

Alternatively have full control

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const toAMPM = hhmmss =&gt; {
  const [hours, minutes, seconds] = hhmmss.split(&quot;:&quot;);
  const formatHours = hours % 12 || 12;
  const ampm = hours &lt; 12 ? &quot;AM&quot; : &quot;PM&quot;;
  return `${+formatHours}:${minutes}:${seconds} ${ampm}`;
};
const convertTime = dateString =&gt; {
  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(&quot;2023-02-28T12:41:41-04:00&quot;));

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月4日 00:44:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75629745.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定