0

I have some JSON that returns a simple date which I am placing in a DIV...

let movieDate = data.release_date;
document.getElementById('movie-date').innerHTML = movieDate;

The output is returned like this...

2021-07-14

I need to change this output to display in two different formats...

  • 14 June 2021
  • 2021

Is there a simple way to do this?

lowercase
  • 1,198
  • 9
  • 34
  • 56
  • 2
    https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript Maybe don't use moment.js, but there are tons of libraries out there that will help you, as well as answers to how to handle this in vanilla JS. – DemiPixel Oct 11 '21 at 05:21
  • The first is parsing to Date then formatting, which has been covered here many times before. The second is simply `movieDate.substring(0,4)` or `movidDate.split(/\D/)[0]`. – RobG Oct 11 '21 at 12:10

1 Answers1

0

Probably the easiest is to use 3rd party library like day.js.

However can be achieved by:

const date = new Date('2021-07-14')

const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"]

// "14 July 2021"
const sDate = `${date.getDate()} ${monthNames[date.getMonth()]} ${date.getFullYear()}`
console.log(sDate)

// 2021
console.log(date.getFullYear())
anmatika
  • 1,581
  • 3
  • 21
  • 29
  • 2021-07-14 will be parsed as UTC, so will be 13 July for users with a negative offset. :-) If you want it treated as local, you'll have to parse it yourself (not hard): `let [Y, M, D] = '2021-07-14'.split(/\W/); let d = new Date(Y, M-1, D)` or `new Date(...'2021-07-14'.split(/\W/).map((v, i) => v - i%2));`. – RobG Oct 11 '21 at 12:13