0

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.

3
  • 2
    There are so many questions about this topic on SO. Please show the code you have tried. Commented Feb 28, 2018 at 9:03
  • 2
    Possible duplicate of How to format a JavaScript date Commented Feb 28, 2018 at 9:05
  • 1
    There are many, many questions on this topic already. What have you tried? Commented Feb 28, 2018 at 9:15

4 Answers 4

4

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>


Sign up to request clarification or add additional context in comments.

Comments

-1

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

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 2822
-1
function formatDate(date) {
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();

return monthNames[monthIndex]+ '.' + day +   + ',' + year;
}

Comments

-1

You 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'));

2 Comments

You should not add your own functions to prototypes like that. Also this question has been answered many, many, many times before. Do not answer but mark it as a duplicate instead.
The OP has a string, not a Date so modifying the Date prototype is unhelpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.