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?
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?
Well to get your date in the 29 Apr, 2018
format you can use two options:
You can use momentjs .format()
method, like this:
var dateStr = '2018-04-29';
var dateWithMoment = moment(dateStr, 'YYYY-MM-DD').format('DD MMM, YYYY');
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>
var givenDate = '2018-04-29'
var resultDate = moment(givenDate, 'YYYY-MM-DD').format('DD MMM, YYYY')
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);
Momentjs should do what you want just fine. (see Li357's answer).
If looking for alternatives, you may want to check out: