0

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?

2

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that makes everything clear now :) I'll accept your answer in 10 minutes
indexing is off for month ... your array is also zero based
Just caught that. Thanks
1

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()

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.