rklitz
rklitz

Reputation: 162

Formatting Dates from JSON using Javascript

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

Upvotes: 1

Views: 52

Answers (2)

Troy Gizzi
Troy Gizzi

Reputation: 2519

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>

Upvotes: 0

timaschew
timaschew

Reputation: 16622

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

Upvotes: 2

Related Questions