-1

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.

Kunj
  • 1,822
  • 21
  • 31
Kunal_89
  • 179
  • 1
  • 9
  • 2
    There are so many questions about this topic on SO. Please show the code you have tried. – t.niese Feb 28 '18 at 09:03
  • 2
    Possible duplicate of [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – str Feb 28 '18 at 09:05
  • 1
    There are [*many, many questions*](https://stackoverflow.com/search?q=%5Bjavascript%5D+reformat+date+string) on this topic already. What have you tried? – RobG Feb 28 '18 at 09:15

4 Answers4

1

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>

ashleedawg
  • 17,207
  • 5
  • 53
  • 80
-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');
asdf_enel_hak
  • 7,114
  • 3
  • 36
  • 77
  • 1
    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 – t.niese Feb 28 '18 at 09:09
-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'));
tigerdi
  • 596
  • 7
  • 13
  • 1
    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. – str Feb 28 '18 at 09:13
  • The OP has a string, not a Date so modifying the Date prototype is unhelpful. – RobG Feb 28 '18 at 09:18
-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;
}
Namburi Akhil
  • 29
  • 1
  • 8