1

I have a problem outputting the date in Javascript. I want to output 2021-03-02T00:00:00+00:00 to March 2, 2021

export function parseDate(dateString) {
  const [date, time] = dateString.split(' ')
  return new Date(`${date}T${time}.000Z`) // Z = UTC
}

export function formatDate(dateString) {
  if (!dateString) return ''

  const date = parseDate(dateString)
  return date.toLocaleString('en', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}



 console.log(formatDate(data?.createdAt))
Joseph
  • 7,042
  • 23
  • 83
  • 181
  • Does this answer your question? [Convert string to datetime](https://stackoverflow.com/questions/5510580/convert-string-to-datetime) – Abdulla Nilam Mar 01 '21 at 05:09
  • Does this answer your question? [Is there a function to get the UTC date in the Locale String Format?](https://stackoverflow.com/questions/55427168/is-there-a-function-to-get-the-utc-date-in-the-locale-string-format) – Suraj Rao Mar 01 '21 at 05:20

2 Answers2

1

This solution is based on your expected output:

const dataSource  = "2021-03-02T00:00:00+00:00";


function getYourDate(source){
  const date = new Date(source);
  const dd = date.getDate();
  const mm = date.toLocaleString('en',{month: 'long'});
  const yyyy = date.getFullYear();
  
  return `${mm} ${dd}, ${yyyy}`;
  }
  
  console.log(getYourDate(dataSource));

TradeCoder
  • 1,832
  • 3
  • 7
  • 18
0

Use toLocaleDateString method with following options as below:

const toReadableDateFormat = (dateStr) => {
  const date = new Date(dateStr);
  const options = { year: 'numeric', month: 'long', day: 'numeric' }
  return date.toLocaleDateString('en', options);
}

console.log(toReadableDateFormat('2021-03-02T00:00:00+00:00'));
Rahul Kumar
  • 3,009
  • 2
  • 16
  • 22