I want to convert string such as '2-12-2018' to Feb. 12, 2018. I have tried many things but still is not showing me the month in format mmm.
-
2There are so many questions about this topic on SO. Please show the code you have tried.t.niese– t.niese2018-02-28 09:03:51 +00:00Commented Feb 28, 2018 at 9:03
-
2Possible duplicate of How to format a JavaScript datestr– str2018-02-28 09:05:35 +00:00Commented Feb 28, 2018 at 9:05
-
1There are many, many questions on this topic already. What have you tried?RobG– RobG2018-02-28 09:15:50 +00:00Commented Feb 28, 2018 at 9:15
Add a comment
|
4 Answers
As others pointed out, there are plenty of existing answers to similar questions, but since JavaScript dates relentlessly drive me batty* I figured I could use the practice... So here's one solution:
function mddyyyy_to_mmmdyyyy(s) {
var s = s.split(/\D/),
dt = new Date(s[2], s[0] - 1, s[1]);
return dt.toLocaleString('en-CA', {
month: 'short',
day: 'numeric',
year: 'numeric'
});
}
document.getElementById('test').innerHTML = mddyyyy_to_mmmdyyyy('2-12-2018');
<div id='test'></div>
- Here's a demo on Codepen.
- Here's documentation on
.toLocaleString()and.split. - Date/time formats to use with
.toLocalString()
Comments
You can do this by using momentjs
var res = moment("2-12-2018").format("DD/MM/YYYY")
var now = moment(res).format('MMM. DD, YYYY');
1 Comment
t.niese
A string in the format
DD/MM/YYYY or D-MM-YYYY is not a date format that should be used in the constructor of moment or new Date because it is neither ISO 8601 nor RFC 2822You can create a function that passes a string as parameter, which creates a Date object from the string, and then returns the formatted date as a string. Such as the below:
var formatDate = function(datestring){
var dt = new Date(datestring);
var month = ['Jan' , 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return (month[dt.getMonth()] +
". " + dt.getDate() +
", " + dt.getFullYear());
}
Then you just call it passing any date string as parameter:
console.log(formatDate('02-12-2017'));