0

I have a string in javascript as 2016-02-27 20:24:39 and I want to convert this as 27th Feb 08:24pm.

What is the easiest way to do in Javascript?

Malaiselvan
  • 1,153
  • 1
  • 16
  • 42
  • @aldanux I can achieve by putting multiple conditions using `date.getHours(), date.getMinutes() etc...` My question is is there a Javascript function like php to easily convert the given date string to any format as we need. – Malaiselvan Feb 27 '16 at 20:52
  • Nothing built-in in JavaScript can do this. You need a third party library in order to achieve this. – corgrath Feb 27 '16 at 20:58
  • Its an duplicate question, check this [question](http://stackoverflow.com/questions/15397372/javascript-new-date-ordinal-st-nd-rd-th) – Shankar Gurav Feb 27 '16 at 21:03
  • 1
    @corgrath - You certainly don't "need" a third-party library: it's not that hard to write a function that does this. (Though I guess the question asks for the "easiest" way, which probably is with moment.js.) – nnnnnn Feb 27 '16 at 21:10
  • @nnnnnn No one said its hard. I said it's not built-in into the language. Besides, I don't agree to reinventing wheels. – corgrath Feb 27 '16 at 21:12

2 Answers2

5

Checkout the JavaScript library called moment.js.

Since the default format for moment is ISO 8601 (YYYY-MM-DD HH:MM:SS), you don't need to tell moment how to parse the input String date (it defaults to ISO 8601), so you can simply write:

var now = "2016-02-27 20:24:39";
var formattedDate = moment(now).format("Do MMM HH:mma");
console.log(formattedDate);

Demo:

https://jsfiddle.net/gekd97dy/

More information about displaying in different formats can be read here:

http://momentjs.com/docs/#/displaying/

corgrath
  • 11,673
  • 15
  • 68
  • 99
3

There is a non-standard Date method toLocaleFormat('%d-%b-%Y'). But appears to only work in Firefox for now.

Better use the date.format library (only 125 lines)

var date = new Date('2016-02-27 20:24:39');
dateFormat(date, "dS mmm, h:MMTT");
Darshan
  • 1,064
  • 7
  • 15