LT86
LT86

Reputation: 655

Parsing date string and retrieving day with Javascript

I've had a look through some of the suggestions in similar answers here but I can't find much that helps me.

Say I have a string that contains a date and a number: 2014-06-24 00:00:00

How would I parse it in a way that I can return this: 2014-06-24 00:00:00 Tuesday

Using date.parse as such:

new Date(Date.parse('2014-06-24 00:00:00'))

gives me the following result:

Tue Jun 24 2014 00:00:00 GMT+0100 (GMT Daylight Time)

Upvotes: 0

Views: 1464

Answers (3)

user288926
user288926

Reputation:

http://momentjs.com is a great, powerful library for easy date manipulation. Worth using if you're doing a lot of it. To get 2014-06-24 00:00:00 Tuesday you could do (after linking in the library, of course).

var m = moment("2014-06-24T00:00:00");
var output = m.format('YYYY-MM-DD hh:mm:ss dddd');

But, really, check out the docs, because this is just the tip of the iceberg: http://momentjs.com/docs/#/parsing/string-format/

Upvotes: 0

Vitorino fernandes
Vitorino fernandes

Reputation: 15951

html

<div id="demo"></div>

js

//var a = new Date();

var a = new Date(Date.parse('2014-06-24 00:00:00'))

var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];

year = a.getFullYear()
month = a.getMonth()
date = a.getDate()
hour = a.getHours()
minutes = a.getMinutes()
seconds = a.getSeconds()
day = a.getDay()

alert(year + "-" + month+ "-" + date + "  " + hour + ":" + minutes + ":" + seconds + "  " +  days[a.getDay()])

document.getElementById("demo").innerHTML = year + "-" + month+ "-" + date + "  " + hour + ":" + minutes + ":" + seconds + "  " +  days[a.getDay()]

you can check the demo here

http://jsfiddle.net/victor_007/7ohh7mjv/

Upvotes: 0

user2053898
user2053898

Reputation: 485

Use methods getDay(),getDate() etc. to extract fields and format resulting string.

There are several JS sprintf implementations: https://stackoverflow.com/a/3932473/2053898 https://github.com/alexei/sprintf.js

Upvotes: 1

Related Questions