-1

as the title described that I want to convert DateTime "2020-12-14 16:07:09" to "9 Jan 2020 " in javascript? is there any easy way of doing it. Any help is appreciated. Thanks in advance.

Bilal
  • 13
  • 2

1 Answers1

0

In one of my previous work i also want this type of, so i created it. i don't know the way to convert but i can tell you how to create.

let guess we want a date 23 January 2019,

It’s simple to create 23 and 2019 for 23 January 2019. We can use getFullYear and getDate to get them.

    const d = new Date(2019, 0, 23)
const year = d.getFullYear() // 2019
const date = d.getDate() // 23

It’s harder to get and January.

To get January, you need to create an object that maps the value of all twelve months to their respective names.

Since Month is zero-indexed, we can use an array instead of an object. It produces the same results.

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

To get January, you need to:

Use getMonth to get the zero-indexed month from the date. Get the month name from months

    const monthIndex = d.getMonth()
const monthName = months[monthIndex]
console.log(monthName) // January

Then, you combine all the variables you created to get the formatted string.

    const formatted = `${date} ${monthName} ${year}`
console.log(formatted) // 23 January 2019

That's it!

If you want like jan,feb,etc... you can change the values in array as per your requirement.

Shadman
  • 31
  • 5