英文:
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("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);
<!-- end snippet -->
Alternatively have full control
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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"));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论