skip to Main Content

I have an array like this:

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" }
]

I need the each objects start date to be formatted into something more readable, while maintaining the arrays structure. Something like "yyyy MM dd hh:mm", so removing dashes, the T, and the seconds.

How do I either update my existing array with formatted date and time, or create a new array with the correct formatting?

4

Answers


  1. You could simply just find and replace.

    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);
    Login or Signup to reply.
  2. You can achieve this by using map method in JavaScript.

    Here, is the sample code for it.

    Link: https://codesandbox.io/s/javascript-forked-gfkhr7?file=/index.js

    Login or Signup to reply.
  3. @Jamiec‘s answer was almost perfect but missing the removal of the time after minutes, so just added a .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);
    Login or Signup to reply.
  4. Hello here is a way of doing it with native 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);
    

    here is a working sand box https://codesandbox.io/s/unruffled-flower-cqdqr3?file=/src/index.js:0-556

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search