NodeJS 如何在对象数组中格式化时间戳?

k2fxgqgv  于 2023-06-29  发布在  Node.js
关注(0)|答案(3)|浏览(130)

我有一个这样的数组:

const myArray = [
    { title: "one", location: "one", start_date_time: "2023-06-28T08:47:00.000Z" },
    { title: "two", location: "two", start_date_time: "2023-06-28T08:47:00.000Z" }
]

我需要每个对象的开始日期被格式化成更可读的东西,同时保持数组结构。类似于“yyyy MM dd hh:mm”,因此删除破折号、T和秒。
如何使用格式化的日期和时间更新现有数组,或使用正确的格式创建新数组?

hpxqektj

hpxqektj1#

你可以简单地找到并替换。

const myArray = [
    { title: "one", location: "one", start_date_time: "2023-06-28T08:47:00.000Z" },
    { title: "two", location: "two", start_date_time: "2023-06-28T08:47:00.000Z" }
]

const result = myArray.map(x => ({
  ...x, 
  start_date_time: x.start_date_time.replaceAll("-"," ").replaceAll("T"," ")
 }));
console.log(result);
slsn1g29

slsn1g292#

@Jamiec的答案几乎完美,但缺少分钟后的时间删除,所以只是添加了一个.slice()。

const myArray = [
    { title: "one", location: "one", start_date_time: "2023-06-28T08:47:00.000Z" },
    { title: "two", location: "two", start_date_time: "2023-06-28T08:47:00.000Z" }
]

const result = myArray.map(x => ({
  ...x, 
  start_date_time: x.start_date_time.replaceAll("-"," ").replaceAll("T"," ").slice(0, x.start_date_time.length - 8)
 }));
console.log(result);
4ktjp1zp

4ktjp1zp3#

Hello这里有一种使用原生JavaScript的方法:

const myArray = [
  {
    title: "one",
    location: "one",
    start_date_time: "2023-06-28T08:47:00.000Z"
  },
  { title: "two", location: "two", start_date_time: "2023-06-28T08:47:00.000Z" }
];

const options = {
  hour: "numeric",
  minute: "numeric",
  second: "numeric",
  year: "numeric",
  month: "numeric",
  day: "numeric",
  timeZone: "UTC"
};

const formattedArray = myArray.map((el) => ({
  ...el,
  start_date_time: new Intl.DateTimeFormat("fr-FR", options)
    .format(new Date(el.start_date_time))
    .replaceAll("/", " ")
}));

console.log(formattedArray);

这是一个工作砂箱https://codesandbox.io/s/unruffled-flower-cqdqr3?file=/src/index.js:0-556

相关问题