1

I am currently getting dates and times sent over to me in the following format through JSON:

2014-10-25 17:00:00

I was wondering if there was a way using Javascript to pull out just the date of that string (maybe using .getDate(); ) as well as grabbing the time out of that string.

I'd also like to be able to format the date and time so it would read as follows:

October 25th, 2014

5:00pm

rklitz
  • 172
  • 10
  • 1
    Look at [`date.js`](http://www.datejs.com/). – PM 77-1 Oct 15 '14 at 21:48
  • 1
    http://momentjs.com/ is exactly what you are looking for. – Amberlamps Oct 15 '14 at 21:52
  • Is there a way through using functions that will allow me to do what this library does? I can't imagine it being that difficult to split this all up into a few strings stored in variables – rklitz Oct 15 '14 at 21:54
  • believe me, you don't want do it by hand ;) http://stackoverflow.com/questions/3552461/how-to-format-javascript-date – timaschew Oct 15 '14 at 22:03

2 Answers2

2

yep, http://momentjs.com is good choice

var moment = require('moment');
var date = moment('2014-10-25 17:00:00');
var out1 = date.format('MMMM Do YYYY'); // October 25th, 2014
var out2 = date.format('h:mma'); // 5:00pm
timaschew
  • 15,034
  • 4
  • 56
  • 73
0

If you have any trouble with the other snippets, here's one specifically targeting a browser-based app. It also uses Moment.js, which is probably the best choice for dealing with dates & times in JavaScript.

var value = '2014-10-25 17:00:00';
var datetime = moment(value);
var date = datetime.format('MMMM Do, YYYY');
var time = datetime.format('h:mma');

document.getElementById('output').innerHTML = date + '<br/>' + time;
<script type="text/javascript" src="http://momentjs.com/downloads/moment.min.js"></script>

<div id="output"></div>
Troy Gizzi
  • 2,403
  • 1
  • 12
  • 14