Home > other >  How to get just the day from ISO string javascript
How to get just the day from ISO string javascript

Time:11-13

I have an ISO date coming back from a server and before I send it to the frontend I want to convert the ISO date to something like this

2011-10-05T14:48:00.000Z

time: {
          day: 'Tue',
          hour: '11:54 AM',
          date: 'May 5, 2019'
        }

I dont want to use a bunch of regex unless I have to, I was hoping I could achieve this with just functions like .toDateString() etc... is there a toDateDayString or something like that?

Here is the snippet of the actual function sending the info back to my frontent.

Id like to be able to to this inline from a promise in .then()

allMessages = [] 

await subClient.conversations.services(convoServiceSid)
           .conversations(convo)
           .messages
           .list({limit: 20})
           .then(messages => messages.forEach(m =>
 allMessages.push({"messagesId": m.conversationSid, "time": m.dateCreated.toDateString() }) ));
//m.dateCreated is always going to be an ISO string, I want to make an object with day, hour, date if possible

res.json(allMessages)

CodePudding user response:

I think you can do it like this:

const date = new Date('2011-10-05T14:48:00.000Z');
const format = {
   day: date.getDay(),
   hour: `${date.getHours()} ${date.getMinutes()}`,
   date: `${date.getMonth()} ${date.getFullYear()}`
};

CodePudding user response:

You can use toLocaleDateString method

function get_time(iso_date_str) {
  const [day, month_date, year, hour] = (
    new Date(iso_date_str).toLocaleDateString('en', {
      weekday: 'short',
      hour: 'numeric',
      minute: 'numeric',
      month: 'short',
      day: 'numeric',
      year: 'numeric',
    })
    .split(/,\s?/)
  );
  return {
    day,
    hour,
    date: month_date   ', '   year
  };
}

console.log(get_time('2011-10-05T14:48:00.000Z'));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related