Get Week of Year in JavaScript Like in PHP

Get week of year in JavaScript like in PHP

You should be able to get what you want here: http://www.merlyn.demon.co.uk/js-date6.htm#YWD.

A better link on the same site is: Working with weeks.

Edit

Here is some code based on the links provided and that posted eariler by Dommer. It has been lightly tested against results at http://www.merlyn.demon.co.uk/js-date6.htm#YWD. Please test thoroughly, no guarantee provided.

Edit 2017

There was an issue with dates during the period that daylight saving was observed and years where 1 Jan was Friday. Fixed by using all UTC methods. The following returns identical results to Moment.js.

/* For a given date, get the ISO week number
*
* Based on information at:
*
* THIS PAGE (DOMAIN EVEN) DOESN'T EXIST ANYMORE UNFORTUNATELY
* http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
*
* Algorithm is to find nearest thursday, it's year
* is the year of the week number. Then get weeks
* between that date and the first day of that year.
*
* Note that dates in one year can be weeks of previous
* or next year, overlap is up to 3 days.
*
* e.g. 2014/12/29 is Monday in week 1 of 2015
* 2012/1/1 is Sunday in week 52 of 2011
*/
function getWeekNumber(d) {
// Copy date so don't modify original
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));
// Get first day of year
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
// Calculate full weeks to nearest Thursday
var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
// Return array of year and week number
return [d.getUTCFullYear(), weekNo];
}

var result = getWeekNumber(new Date());
document.write('It\'s currently week ' + result[1] + ' of ' + result[0]);

Show week number with Javascript?

Simply add it to your current code, then call (new Date()).getWeek()

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

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

var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var now = new Date();
document.write(dayNames[now.getDay()] + " (" + weekNumber + ").");
</script>

JavaScript Date.getWeek()?

/**
* Returns the week number for this date. dowOffset is the day of week the week
* "starts" on for your locale - it can be from 0 to 6. If dowOffset is 1 (Monday),
* the week returned is the ISO 8601 week number.
* @param int dowOffset
* @return int
*/
Date.prototype.getWeek = function (dowOffset) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */

dowOffset = typeof(dowOffset) == 'number' ? dowOffset : 0; //default dowOffset to zero
var newYear = new Date(this.getFullYear(),0,1);
var day = newYear.getDay() - dowOffset; //the day of week the year begins on
day = (day >= 0 ? day : day + 7);
var daynum = Math.floor((this.getTime() - newYear.getTime() -
(this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
var weeknum;
//if the year starts before the middle of a week
if(day < 4) {
weeknum = Math.floor((daynum+day-1)/7) + 1;
if(weeknum > 52) {
nYear = new Date(this.getFullYear() + 1,0,1);
nday = nYear.getDay() - dowOffset;
nday = nday >= 0 ? nday : nday + 7;
/*if the next year starts before the middle of
the week, it is week #1 of that year*/
weeknum = nday < 4 ? 1 : 53;
}
}
else {
weeknum = Math.floor((daynum+day-1)/7);
}
return weeknum;
};

Usage:

var mydate = new Date(2011,2,3); // month number starts from 0
// or like this
var mydate = new Date('March 3, 2011');
alert(mydate.getWeek());

Source

Get week number with week starting from sunday

Your issue is here:

var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);

That code is for ISO weeks and adjusts Sunday's day number to 7 and sets the date to Thursday, where the week is Monday to Sunday.

You want weeks Sunday to Saturday and want the week of the Sunday, so use:

var dayNum = d.getUTCDay();
d.setUTCDate(d.getUTCDate() - dayNum);

which can be reduced to:

d.setUTCDate(d.getUTCDate() - d.getUTCDay());

 Date.prototype.getWeekNumber = function () {

var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));

d.setUTCDate(d.getUTCDate() - d.getUTCDay());

var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));

return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);

};



var c = new Date(2017,7,26);

console.log(c.getWeekNumber() + ':' + c.toString());

var d = new Date(2017,7,27);

console.log(d.getWeekNumber() + ':' + d.toString());

Get the current week using JavaScript without additional libraries ? [SO examples are broken]

The algorithm is to use the week number of the following Saturday. So get the following Saturday, then use it's year for the 1st of Jan. If it's not a Sunday, go to the previous Sunday. Then get the number of weeks from there. It might sound a bit convoluted, but it's only a few lines of code. Most of the following is helpers for playing.

Hopefully the comments are sufficient, getWeekNumber returns an array of [year, weekNumber]. Tested against the Mac OS X Calendar, which seems to use the same week numbering. Please test thoroughly, particularly around daylight saving change over.

/* Get week number in year based on:

* - week starts on Sunday

* - week number and year is that of the next Saturday,

* or current date if it's Saturday

* 1st week of 2011 starts on Sunday 26 December, 2010

* 1st week of 2017 starts on Sunday 1 January, 2017

*

* Calculations use UTC to avoid daylight saving issues.

*

* @param {Date} date - date to get week number of

* @returns {number[]} year and week number

*/

function getWeekNumber(date) {

// Copy date as UTC to avoid DST

var d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));

// Shift to the following Saturday to get the year

d.setUTCDate(d.getUTCDate() + 6 - d.getUTCDay());

// Get the first day of the year

var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));

yearStart.setUTCDate(yearStart.getUTCDate() - yearStart.getUTCDay());

// Get difference between yearStart and d in milliseconds

// Reduce to whole weeks

return [d.getUTCFullYear(), (Math.ceil((d - yearStart) / 6.048e8))];

}

// Helper to format dates

function fDate(d) {

var opts = {weekday:'short',month:'short',day:'numeric',year:'numeric'};

return d.toLocaleString(undefined, opts);

}

// Parse yyyy-mm-dd as local

function pDate(s){

var b = (s+'').split(/\D/);

var d = new Date(b[0],b[1]-1,b[2]);

return d.getMonth() == b[1]-1? d : new Date(NaN);

}

// Handle button click

function doButtonClick(){

var d = pDate(document.getElementById('inp0').value);

var span = document.getElementById('weekNumber');

if (isNaN(d)) {

span.textContent = 'Invalid date';

} else {

let [y,w] = getWeekNumber(d);

span.textContent = `${fDate(d)} is in week ${w} of ${y}`;

}

}
Date:<input id="inp0" placeholder="yyyy-mm-dd">

<button type="button" onclick="doButtonClick()">Get week number</button><br>

<span id="weekNumber"></span>

Getting dates for week number last year, php

You could use setISODate for that:

$date = new DateTime();
$date->setISODate(date("Y")-1, date("W"));

$monday = $date->format('Y-m-d');
$friday = $date->modify('+4 days')->format('Y-m-d');

print($monday);
print($friday);

How to get week number from date input in javascript?

function getWeekNumber(thisDate) {
var dt = new Date(thisDate);
var thisDay = dt.getDate();

var newDate = dt;
newDate.setDate(1); // first day of month
var digit = newDate.getDay();

var Q = (thisDay + digit) / 7;

var R = (thisDay + digit) % 7;

if (R !== 0) return Math.ceil(Q);
else return Q;}

getWeekNumber("07/31/2016");

Javascript - How do i get every date in a week from a given week number and year

Here's an example building on top of: javascript calculate date from week number

Get the first date of the week, then return an array of 7 elements, incrementing the date for each element.

If the day number goes above the number of days in the month, then add one to the month temp.m and reset the day temp.d equal to one.

function getISOWeek(w, y) {
var simple = new Date(y, 0, 1 + (w - 1) * 7);
var dow = simple.getDay();
var ISOweekStart = simple;
if (dow <= 4)
ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
else
ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
const temp = {
d: ISOweekStart.getDate(),
m: ISOweekStart.getMonth(),
y: ISOweekStart.getFullYear(),
}
//console.log(ISOweekStart)
const numDaysInMonth = new Date(temp.y, temp.m + 1, 0).getDate()

return Array.from({length: 7}, _ => {
if (temp.d > numDaysInMonth){
temp.m +=1;
temp.d = 1;
// not needed, Date(2020, 12, 1) == Date(2021, 0, 1)
/*if (temp.m >= 12){
temp.m = 0
temp.y +=1
}*/
}
return new Date(temp.y, temp.m, temp.d++).toUTCString()
});
}

// var weekNumber = "week + " " + year"; //"35 2020"
const weekNumber = "53 2020";

const weekYearArr = weekNumber.split(" ").map(n => parseInt(n))

const weekOut = getISOWeek(...weekYearArr)

console.log(weekOut);

javascript function to calculate the numbers of the calendar weeks in a provided month

You can approach this in a similar manner to getting the week number of the year, e.g.

// Helper: return Monday of first week of given month. 
// Might be in previous month.
// First week of month is the one that contains the 4th of month
function getFirstMondayWeek(date) {
// Get 4th of month
let d = new Date(date.getFullYear(), date.getMonth(), 4);
// Move to Monday on or before 4th
d.setDate(d.getDate() - (d.getDay() || 7) + 1);
return d;
}

// Helper: return number of days in month for Date
function getDaysInMonth(date) {
return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
}

// Helper: return name of month for Date
function getMonthName(date) {
return date.toLocaleString('default',{month:'long'});
}

// Return week number in month for given Date,
// may be in last week of previous month.
// First day of week is Monday.
function getWeekOfMonth(date) {

// Copy date with time set to 00:00:00
let startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());

// Get start of week
let weekStart = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate() - (startDate.getDay() || 7) + 1);

// Get start of first week of month (might be in previous month)
let testWeek = new Date(weekStart.getFullYear(), weekStart.getMonth(), 4);
let monthStart = getFirstMondayWeek(testWeek);
// Month start might be in previous month, so get right month name
let monthName = getMonthName(testWeek);

// If date is three days or less from end of month, might be in first week of next month
if (startDate.getDate() > (getDaysInMonth(startDate) - 5)) {
testWeek = new Date(startDate.getFullYear(), startDate.getMonth() + 1, 4);
let nextMonthStart = getFirstMondayWeek(testWeek);

// If in first week of next month, update related variables
if (startDate >= nextMonthStart) {
monthStart = nextMonthStart;
monthName = getMonthName(testWeek);
}
}

// Calc week number
let weekNum = Math.floor(Math.round((weekStart - monthStart)/8.64e7/7)) + 1;
return {weekNum, monthName};
}

// Examples
[new Date(2021, 2, 1), // 1 Mar 2021
new Date(2021, 7, 1), // 1 Aug 2021
new Date(2021, 7,30), // 30 Aug 2021
new Date(2021,11,25), // 30 Aug 2021
new Date(2022,10, 1), // 1 Nov 2021
new Date(2022, 0, 2), // 2 Jan 2022
new Date() // Today
].forEach(date => {
let {weekNum, monthName} = getWeekOfMonth(date);
console.log(`${date.toDateString()} is in ${monthName.slice(0,3)} week ${weekNum}`);
});

// Check that the sum of the weeks in the months
// of a year equals the weeks in the year
// 4th day from end (last day - 3) is always in last week
function getWeeksInMonth(date) {
let testDate = new Date(date.getFullYear(), date.getMonth(), getDaysInMonth(date) - 3);
return getWeekOfMonth(testDate).weekNum;
}

function getWeeksInYear(date) {
let year = date.getFullYear();
let yearStart = getFirstMondayWeek(new Date(year, 0, 4));
let yearEnd = new Date(year, 11, 28);
yearEnd.setDate(yearEnd.getDate() - (yearEnd.getDay() || 7) + 1);
return Math.round((yearEnd - yearStart)/8.64e7/7) + 1;
}

// Sum weeks in each month for year of date
function sumWeeksInMonths(date) {
let d = new Date(date.getFullYear(), 0, 1);
let sum = 0;
for (let i=0; i<12; i++) {
sum += getWeeksInMonth(d);
d.setMonth(d.getMonth() + 1);
}
return sum;
}

for (let i=0, d=new Date(2020, 0),a,b; i<20; i++) {
a = getWeeksInYear(d);
b = sumWeeksInMonths(d);
console.log(`${d.getFullYear()} has ${a} weeks` +
`, month week sum is ${b}`);
d.setFullYear(d.getFullYear() + 1);
}

Calculate date from week number in JavaScript

function getDateOfWeek(w, y) {
var d = (1 + (w - 1) * 7); // 1st of January + 7 days for each week

return new Date(y, 0, d);
}

This uses the simple week definition, meaning the 20th week of 2013 is May 14.

To calculate the date of the start of a given ISO8601 week (which will always be a Monday)

function getDateOfISOWeek(w, y) {
var simple = new Date(y, 0, 1 + (w - 1) * 7);
var dow = simple.getDay();
var ISOweekStart = simple;
if (dow <= 4)
ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
else
ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
return ISOweekStart;
}

Result: the 20th week of 2013 is May 13, which can be confirmed here.



Related Topics



Leave a reply



Submit