0

How I make a sintax to convert date format from default format (yyyy-mm-dd) to english format like December 11th, 2013 using Javascript function?

Thank you

Rizky
  • 3
  • 4
  • 1
    possible duplicate of [Where can I find documentation on formatting a date in JavaScript](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – philshem Mar 06 '14 at 10:32

3 Answers3

3

You could use moment.js

Moment.js 2.7.0

Moment was designed to work both in the browser and in Node.JS. Parse, validate, manipulate, and display dates in javascript.

and it is also available on cdnjs.com.

ale
  • 10,012
  • 5
  • 40
  • 49
wayne
  • 3,410
  • 19
  • 11
  • 1
    Yes, moment.js is the best for this. Also if you use angular, you can use a directive: https://github.com/urish/angular-moment – Capaj Mar 06 '14 at 10:35
1
var str_date = "1983-24-12",
    arr_date = str_date.split('-'),
    months   = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

var new_date=months[arr_date[2]] + ' ' + arr_date[1] + ', ' + arr_date[0]);

http://jsfiddle.net/TN7NE/

Edit

You can add an ordinal using the following:

function addOrdinal(n) {
    var ord = [,'st','nd','rd'];
    var a = n%100;
    return n + (ord[a>20? a%10 :a] || 'th');
}

e.g.

addOrdinal(1); // 1st
RobG
  • 142,382
  • 31
  • 172
  • 209
  • but, "dd" also including e.g (1st, 2nd, 3th, 4th, ..., 11th, 12th) what's way that must I do? – Rizky Mar 06 '14 at 10:38
1

You can use a function like this:

function formatDate(date) {
  months = ['January', 'February', 'March', 'April',
            'May', 'June', 'July', 'August',
            'September', 'October', 'November', 'December'];
  dateSplit = date.split('-');
  year = dateSplit[0];
  month = months[parseInt(dateSplit[1]) - 1];
  day = parseInt(dateSplit[2]);
  switch(day) {
    case 1:
    case 21:
    case 31:
      day += 'st';
      break;
    case 2:
    case 22:
      day += 'nd';
      break;
    case 3:
    case 23:
      day += 'rd';
      break;
    default:
      day += 'th';
  }
  return month + ' ' + day + ', ' + year;
}
gloover
  • 11
  • 2
  • Adding an ordinal can be much simpler (and your function fails with 21, 22, 23 and 31). – RobG Mar 06 '14 at 11:24
  • I've fixed that cases. And RobG is right: the function addOrdinal in other answer is more elegant. – gloover Mar 06 '14 at 12:33