[javascript] Show week number with Javascript?

I have the following code that is used to show the name of the current day, followed by a set phrase.

<script type="text/javascript"> 
    <!-- 
    // Array of day names
    var dayNames = new Array(
    "It's Sunday, the weekend is nearly over",
    "Yay! Another Monday",
     "Hello Tuesday, at least you're not Monday",
     "It's Wednesday. Halfway through the week already",
     "It's Thursday.",
     "It's Friday - Hurray for the weekend",
    "Saturday Night Fever");
    var now = new Date();
    document.write(dayNames[now.getDay()] + ".");
     // -->
</script>

What I would like to do is have the current week number in brackets after the phrase. I have found the following code:

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(),0,1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
} 

Which was taken from http://javascript.about.com/library/blweekyear.htm but I have no idea how to add it to existing javascript code.

This question is related to javascript date calendar

The answer is


I was coding in the dark (a challenge) and couldn't lookup or test my code.

I forgot what round up was called (Math.celi) So I wanted to be extra sure i got it right and came up with this code.

_x000D_
_x000D_
var elm = document.createElement('input')_x000D_
elm.type = 'week'_x000D_
elm.valueAsDate = new Date()_x000D_
var week = elm.value.split('W').pop()_x000D_
_x000D_
console.log(week)
_x000D_
_x000D_
_x000D_ Just a proof of concept of how you can get the week in any other way

But still i recommend any other solution that isn't required by the DOM.


You could find this fiddle useful. Just finished. https://jsfiddle.net/dnviti/ogpt920w/ Code below also:

_x000D_
_x000D_
/** _x000D_
 * Get the ISO week date week number _x000D_
 */  _x000D_
Date.prototype.getWeek = function () {  _x000D_
  // Create a copy of this date object  _x000D_
  var target  = new Date(this.valueOf());  _x000D_
_x000D_
  // ISO week date weeks start on monday  _x000D_
  // so correct the day number  _x000D_
  var dayNr   = (this.getDay() + 6) % 7;  _x000D_
_x000D_
  // ISO 8601 states that week 1 is the week  _x000D_
  // with the first thursday of that year.  _x000D_
  // Set the target date to the thursday in the target week  _x000D_
  target.setDate(target.getDate() - dayNr + 3);  _x000D_
_x000D_
  // Store the millisecond value of the target date  _x000D_
  var firstThursday = target.valueOf();  _x000D_
_x000D_
  // Set the target to the first thursday of the year  _x000D_
  // First set the target to january first  _x000D_
  target.setMonth(0, 1);  _x000D_
  // Not a thursday? Correct the date to the next thursday  _x000D_
  if (target.getDay() != 4) {  _x000D_
    target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);  _x000D_
  }  _x000D_
_x000D_
  // The weeknumber is the number of weeks between the   _x000D_
  // first thursday of the year and the thursday in the target week  _x000D_
  return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000  _x000D_
}  _x000D_
_x000D_
/** _x000D_
* Get the ISO week date year number _x000D_
*/  _x000D_
Date.prototype.getWeekYear = function ()   _x000D_
{  _x000D_
  // Create a new date object for the thursday of this week  _x000D_
  var target  = new Date(this.valueOf());  _x000D_
  target.setDate(target.getDate() - ((this.getDay() + 6) % 7) + 3);  _x000D_
_x000D_
  return target.getFullYear();  _x000D_
}_x000D_
_x000D_
/** _x000D_
 * Convert ISO week number and year into date (first day of week)_x000D_
 */ _x000D_
var getDateFromISOWeek = function(w, y) {_x000D_
  var simple = new Date(y, 0, 1 + (w - 1) * 7);_x000D_
  var dow = simple.getDay();_x000D_
  var ISOweekStart = simple;_x000D_
  if (dow <= 4)_x000D_
    ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);_x000D_
  else_x000D_
    ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());_x000D_
  return ISOweekStart;_x000D_
}_x000D_
_x000D_
var printDate = function(){_x000D_
  /*var dateString = document.getElementById("date").value;_x000D_
 var dateArray = dateString.split("/");*/ // use this if you have year-week in the same field_x000D_
_x000D_
  var dateInput = document.getElementById("date").value;_x000D_
  if (dateInput == ""){_x000D_
    var date = new Date(); // get today date object_x000D_
  }_x000D_
  else{_x000D_
    var date = new Date(dateInput); // get date from field_x000D_
  }_x000D_
_x000D_
  var day = ("0" + date.getDate()).slice(-2); // get today day_x000D_
  var month = ("0" + (date.getMonth() + 1)).slice(-2); // get today month_x000D_
  var fullDate = date.getFullYear()+"-"+(month)+"-"+(day) ; // get full date_x000D_
  var year = date.getFullYear();_x000D_
  var week = ("0" + (date.getWeek())).slice(-2);_x000D_
  var locale= "it-it";_x000D_
  _x000D_
  document.getElementById("date").value = fullDate; // set input field_x000D_
_x000D_
  document.getElementById("year").value = year;_x000D_
  document.getElementById("week").value = week; // this prototype has been written above_x000D_
_x000D_
  var fromISODate = getDateFromISOWeek(week, year);_x000D_
  _x000D_
 var fromISODay = ("0" + fromISODate.getDate()).slice(-2);_x000D_
  var fromISOMonth = ("0" + (fromISODate.getMonth() + 1)).slice(-2);_x000D_
  var fromISOYear = date.getFullYear();_x000D_
  _x000D_
  // Use long to return month like "December" or short for "Dec"_x000D_
  //var monthComplete = fullDate.toLocaleString(locale, { month: "long" }); _x000D_
_x000D_
  var formattedDate = fromISODay + "-" + fromISOMonth + "-" + fromISOYear;_x000D_
_x000D_
  var element = document.getElementById("fullDate");_x000D_
_x000D_
  element.value = formattedDate;_x000D_
}_x000D_
_x000D_
printDate();_x000D_
document.getElementById("convertToDate").addEventListener("click", printDate);
_x000D_
*{_x000D_
  font-family: consolas_x000D_
}
_x000D_
<label for="date">Date</label>_x000D_
<input type="date" name="date" id="date" style="width:130px;text-align:center" value="" />_x000D_
<br /><br />_x000D_
<label for="year">Year</label>_x000D_
<input type="year" name="year" id="year" style="width:40px;text-align:center" value="" />_x000D_
-_x000D_
<label for="week">Week</label>_x000D_
<input type="text" id="week" style="width:25px;text-align:center" value="" />_x000D_
<br /><br />_x000D_
<label for="fullDate">Full Date</label>_x000D_
<input type="text" id="fullDate" name="fullDate" style="width:80px;text-align:center" value="" />_x000D_
<br /><br />_x000D_
<button id="convertToDate">_x000D_
Convert Date_x000D_
</button>
_x000D_
_x000D_
_x000D_

It's pure JS. There are a bunch of date functions inside that allow you to convert date into week number and viceversa :)


Consider using my implementation of "Date.prototype.getWeek", think is more accurate than the others i have seen here :)

Date.prototype.getWeek = function(){
    // We have to compare against the first monday of the year not the 01/01
    // 60*60*24*1000 = 86400000
    // 'onejan_next_monday_time' reffers to the miliseconds of the next monday after 01/01

    var day_miliseconds = 86400000,
        onejan = new Date(this.getFullYear(),0,1,0,0,0),
        onejan_day = (onejan.getDay()==0) ? 7 : onejan.getDay(),
        days_for_next_monday = (8-onejan_day),
        onejan_next_monday_time = onejan.getTime() + (days_for_next_monday * day_miliseconds),
        // If one jan is not a monday, get the first monday of the year
        first_monday_year_time = (onejan_day>1) ? onejan_next_monday_time : onejan.getTime(),
        this_date = new Date(this.getFullYear(), this.getMonth(),this.getDate(),0,0,0),// This at 00:00:00
        this_time = this_date.getTime(),
        days_from_first_monday = Math.round(((this_time - first_monday_year_time) / day_miliseconds));

    var first_monday_year = new Date(first_monday_year_time);

    // We add 1 to "days_from_first_monday" because if "days_from_first_monday" is *7,
    // then 7/7 = 1, and as we are 7 days from first monday,
    // we should be in week number 2 instead of week number 1 (7/7=1)
    // We consider week number as 52 when "days_from_first_monday" is lower than 0,
    // that means the actual week started before the first monday so that means we are on the firsts
    // days of the year (ex: we are on Friday 01/01, then "days_from_first_monday"=-3,
    // so friday 01/01 is part of week number 52 from past year)
    // "days_from_first_monday<=364" because (364+1)/7 == 52, if we are on day 365, then (365+1)/7 >= 52 (Math.ceil(366/7)=53) and thats wrong

    return (days_from_first_monday>=0 && days_from_first_monday<364) ? Math.ceil((days_from_first_monday+1)/7) : 52;
}

You can check my public repo here https://bitbucket.org/agustinhaller/date.getweek (Tests included)


By adding the snippet you extend the Date object.

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(),0,1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}

If you want to use this in multiple pages you can add this to a seperate js file which must be loaded first before your other scripts executes. With other scripts I mean the scripts which uses the getWeek() method.


With that code you can simply;

document.write(dayNames[now.getDay()] + " (" + now.getWeek() + ").");

(You will need to paste the getWeek function above your current script)


Some of the code I see in here fails with years like 2016, in which week 53 jumps to week 2.

Here is a revised and working version:

Date.prototype.getWeek = function() { 

  // Create a copy of this date object  
  var target  = new Date(this.valueOf());  

  // ISO week date weeks start on monday, so correct the day number  
  var dayNr   = (this.getDay() + 6) % 7;  

  // Set the target to the thursday of this week so the  
  // target date is in the right year  
  target.setDate(target.getDate() - dayNr + 3);  

  // ISO 8601 states that week 1 is the week with january 4th in it  
  var jan4    = new Date(target.getFullYear(), 0, 4);  

  // Number of days between target date and january 4th  
  var dayDiff = (target - jan4) / 86400000;    

  if(new Date(target.getFullYear(), 0, 1).getDay() < 5) {
    // Calculate week number: Week 1 (january 4th) plus the    
    // number of weeks between target date and january 4th    
    return 1 + Math.ceil(dayDiff / 7);    
  }
  else {  // jan 4th is on the next week (so next week is week 1)
    return Math.ceil(dayDiff / 7); 
  }
}; 

In case you already use jquery-ui (specifically datepicker):

Date.prototype.getWeek = function () { return $.datepicker.iso8601Week(this); }

Usage:

var myDate = new Date();
myDate.getWeek();

More here: UI/Datepicker/iso8601Week

I realize this isn't a general solution as it incurs a dependency. However, considering the popularity of jquery-ui this might just be a simple fit for someone - as it was for me.


All the proposed approaches may give wrong results because they don’t take into account summer/winter time changes. Rather than calculating the number of days between two dates using the constant of 86’400’000 milliseconds, it is better to use an approach like the following one:

getDaysDiff = function (dateObject0, dateObject1) {
    if (dateObject0 >= dateObject1) return 0;
    var d = new Date(dateObject0.getTime());
    var nd = 0;
    while (d <= dateObject1) {
        d.setDate(d.getDate() + 1);
        nd++;
    }
    return nd-1;
};

It looks like this function I found at weeknumber.net is pretty accurate and easy to use.

// This script is released to the public domain and may be used, modified and
// distributed without restrictions. Attribution not necessary but appreciated.
// Source: http://weeknumber.net/how-to/javascript 

// Returns the ISO week of the date.
Date.prototype.getWeek = function() {
  var date = new Date(this.getTime());
  date.setHours(0, 0, 0, 0);
  // Thursday in current week decides the year.
  date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
  // January 4 is always in week 1.
  var week1 = new Date(date.getFullYear(), 0, 4);
  // Adjust to Thursday in week 1 and count number of weeks from date to week1.
  return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}

If you're lucky like me and need to find the week number of the month a little adjust will do it:

// Returns the week in the month of the date.
Date.prototype.getWeekOfMonth = function() {
  var date = new Date(this.getTime());
  date.setHours(0, 0, 0, 0);
  // Thursday in current week decides the year.
  date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
  // January 4 is always in week 1.
  var week1 = new Date(date.getFullYear(), date.getMonth(), 4);
  // Adjust to Thursday in week 1 and count number of weeks from date to week1.
  return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}

If you want something that works and is future-proof, use a library like MomentJS.

moment(date).week();
moment(date).isoWeek()

http://momentjs.com/docs/#/get-set/week/


If you already use Angular, then you could profit $filter('date').

For example:

var myDate = new Date();
var myWeek = $filter('date')(myDate, 'ww');

Martin Schillinger's version seems to be the strictly correct one.

Since I knew I only needed it to work correctly on business week days, I went with this simpler form, based on something I found online, don't remember where:

ISOWeekday = (0 == InputDate.getDay()) ? 7 : InputDate.getDay();
ISOCalendarWeek = Math.floor( ( ((InputDate.getTime() - (new Date(InputDate.getFullYear(),0,1)).getTime()) / 86400000) - ISOWeekday + 10) / 7 );

It fails in early January on days that belong to the previous year's last week (it produces CW = 0 in those cases) but is correct for everything else.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to calendar

Moment.js get day name from date HTML Input Type Date, Open Calendar by default Check if a given time lies between two times regardless of date Creating java date object from year,month,day How to set time to 24 hour format in Calendar How to get Month Name from Calendar? Get first date of current month in java Specify the date format in XMLGregorianCalendar Getting last day of the month in a given string date How to change TIMEZONE for a java.util.Calendar/Date