-2

I have the date 2013-03-10 how can i get March 10,2013. I tried a lot with Date function in javascript but can't get correct format as given above.Help should be appreciated.

CodeBreaker
  • 395
  • 2
  • 9
  • 1
    Please share what you have already tried. Also, a tip: https://momentjs.com/ – BenM Jul 16 '19 at 10:41
  • if you're happy to use momentjs, I would strongly recommend that for handling dates in javascript - https://momentjs.com/ - look under the 'format' section – Huw Davies Jul 16 '19 at 10:42
  • 3
    [Every single possible JavaScript date parsing or formatting question has already been asked and answered](/search?q=%5Bjs%5D+format+date). Please **search** before posting. More about searching [here](/help/searching). – T.J. Crowder Jul 16 '19 at 10:43
  • @HuwDavies i wast to use only basic javascript and their Date() functions. – CodeBreaker Jul 16 '19 at 10:44
  • I searched a lot can you please mention a link in comment @T.J.Crowder – CodeBreaker Jul 16 '19 at 10:45

2 Answers2

0

I'm going to answer this question simply because I would like to share that it is not necessary to use the Date object nor heavy libraries like MomentJS if all you need is to support those two formats.

The solution is basically this:

  1. Prepare a mapping between month number and month names.
  2. Break the input date in YYYY-MM-DD format into its individual components (e.g., split with '-')
  3. Get the month name from the map constructed in step 1.
  4. Reconstruct the date in target format using simple string interpolation.

Something like this:

var MONTH_NAMES = {
  1: 'January',
  2: 'February',
  3: 'March',
  ....
};

function convertDateFormat(inputDate) {
  var components = inputDate.split('-');
  var year = components[0];
  var month = MONTH_NAMES[components[1]];
  var day = components[2];
  return month + ' ' + day + ', ' + year;
}

convertDateFormat('2013-03-10');
0

You can use Date.toLocaleString :

var options = { month: 'long', day: 'numeric', year: 'numeric' }

console.log( new Date('2013-03-10').toLocaleString('en-US', options) )
Slai
  • 22,144
  • 5
  • 45
  • 53
  • can you please tell me if i put date with time then how can i get like March 10, 2013, 7:30 PM @Slai – CodeBreaker Jul 16 '19 at 11:18
  • @CodeBreaker you can check the link in my answer for the other options, and don't ask more than one question per question – Slai Jul 16 '19 at 11:25