Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does getDay() comply with ISO 8601?

Tags:

javascript

I'm having real trouble working out whether JavaScript's getDay() method (http://www.w3schools.com/jsref/jsref_getday.asp) complies with ISO 8601.

getDay() returns 0 for Sunday, 1 for Monday etc..

The documentation recommends mapping to day names like this:

var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
...
var n = weekday[(new Date()).getDay()];

I can only see that the ISO standard defines Monday as the first day of the week. I would assume this means Monday should be 0, not Sunday.

Does anyone have any experience with this? Can you clarify and would you recommend overriding the method to make Monday the first day of the week?

like image 386
John H Avatar asked Jan 11 '13 01:01

John H


People also ask

How do I convert a date to ISO 8601?

The date. toISOString() method is used to convert the given date object's contents into a string in ISO format (ISO 8601) i.e, in the form of (YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss.

Is ISO 8601 always UTC?

Date.prototype.toISOString() The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ , respectively). The timezone is always zero UTC offset, as denoted by the suffix Z .

What is the ISO 8601 calendar?

All weeks in the ISO-8601 Week-Based calendar have exactly 7 days, start on a Monday, and each week belongs to single year. Unlike the Gregorian calendar, there are no weeks that extend across years. Each ISO-8601 year is either a Long or a Short year, with 52 or 53 weeks depending on when the ISO-8601 year begins.

How do I find the timezone in an ISO date?

Converts a date to extended ISO format (ISO 8601), including timezone offset. Use Date. prototype. getTimezoneOffset() to get the timezone offset and reverse it.


2 Answers

var weekday=new Array(7);
weekday[0]="Monday";
weekday[1]="Tuesday";
weekday[2]="Wednesday";
...
var n = weekday[((new Date()).getDay() + 6) % 7 + 1];

or extend the Date prototype:

Date.prototype.getISODay = function(){ return (this.getDay() + 6) % 7 + 1; }

and then use

var n = weekday[(new Date()).getISODay()];
like image 94
ic3b3rg Avatar answered Sep 23 '22 06:09

ic3b3rg


How the weekdays are represented only matters if you want to use a date format where the weekday actually is represented as a number, e.g. the YYYY-Www-D format, or if you want to get the week number for a specific date.

Otherwise it doesn't matter how the weekdays are represented numerically. A monday is still a monday.

like image 25
Guffa Avatar answered Sep 25 '22 06:09

Guffa