0

I have a date like this 2018-04-29 But I need the date in this format 29 Apr, 2018 How can i do it in nodejs?

I couldnot figure it out using moment js.

Is there any other method?

cнŝdk
  • 28,676
  • 7
  • 47
  • 67
Ujwal
  • 53
  • 10

4 Answers4

2

Well to get your date in the 29 Apr, 2018 format you can use two options:

  1. Use momentjs:

You can use momentjs .format() method, like this:

var dateStr = '2018-04-29';
var dateWithMoment = moment(dateStr, 'YYYY-MM-DD').format('DD MMM, YYYY');
  1. Or use Date#toLocaleString() method.

You can use the toLocaleString() method like this:

var options = {
  year: "numeric",
  month: "short",
  day: "numeric"
};
console.log((new Date(dateStr)).toLocaleString("en-US", options));

Demo:

This is a Demo showing both ways of doing this:

var dateStr = '2018-04-29';
var dateWithMoment = moment(dateStr, 'YYYY-MM-DD').format('DD MMM, YYYY');

console.log(dateWithMoment);


var options = {
  year: "numeric",
  month: "short",
  day: "numeric"
};
console.log((new Date(dateStr)).toLocaleString("en-US", options));
<script src="http://momentjs.com/downloads/moment.js"></script>
cнŝdk
  • 28,676
  • 7
  • 47
  • 67
1
var givenDate = '2018-04-29'
var resultDate = moment(givenDate, 'YYYY-MM-DD').format('DD MMM, YYYY')
Mani Kumar
  • 26
  • 2
0

If moment isn't working for you, you could use vanilla js like so:

const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

// Date to convert
let myDate = "2018-04-29";
let components = myDate.split('-'); 

// 29 Apr, 2018
let newDate = components[2] + " " +monthNames[parseInt(components[1]) - 1] +", " +components[0];
console.log(newDate);
Nick Parsons
  • 31,322
  • 6
  • 25
  • 44
0

Momentjs should do what you want just fine. (see Li357's answer).

If looking for alternatives, you may want to check out:

Mehmet Fatih Yıldız
  • 1,526
  • 14
  • 23