Xeen
Xeen

Reputation: 7003

How to parse the date portion of a datetime string in JavaScript?

I have this datetime string

Tue, 20 Oct 2015 17:14:47 +0200

I need to return the date portion from this. In other words, get date, month and year from it.

Currently I've done:

pub_date = new Date("Tue, 20 Oct 2015 17:14:47 +0200")
day      = pub_date.getDate()
month    = pub_date.getMonth()
year     = pub_date.getYear()

Only the day gets returned correctly. month and year return the wrong results. What would be more correct?

Upvotes: 0

Views: 105

Answers (3)

MzTr
MzTr

Reputation: 11

What results do you expect exactly ? .getMonth() should return you 9, which is correct because monthes are numbered 0 to 11.

Use .getFullYear() instead of getYear(), that should return you 2015.

Upvotes: 1

arcyqwerty
arcyqwerty

Reputation: 10695

According to the docs:

Date.prototype.getMonth()

Returns the month (0-11) in the specified date according to local time.

Date.prototype.getFullYear()

Returns the year (4 digits for 4-digit years) of the specified date according to local time.

So you'd want:

pub_date = new Date("Tue, 20 Oct 2015 17:14:47 +0200")
day      = pub_date.getDate()
month    = pub_date.getMonth() + 1
year     = pub_date.getFullYear()

Upvotes: 1

Richard Hamilton
Richard Hamilton

Reputation: 26444

It should be pub_date.getFullYear(). getYear() has been deprecated.

http://www.w3schools.com/jsref/jsref_getfullyear.asp

Also, the month returns a number from 0 to 11. You should create a months array and access the result of getMonth.

var months = ["January", "February", "March", "April", "May", "June", "July", 
              "August", "September", "October", "November", "December"];
month = months[pub_date.getMonth()];

Or if you're using angular, you can use the built-in date filter

{{ date | format: 'MMMM' }}

https://docs.angularjs.org/api/ng/filter/date

Upvotes: 3

Related Questions