Going through weeks is automatically changing on wednesday rather than sunday/monday - javascript

I'm looking for some help with my coursework as I've spent the last 8 hours trying to find a way to do what i'm trying to accomplish.
Now I have to use JavaScript, cannot use plugins but i can use the jQuery Library.
I'm basically trying to assign weeks to the semesters of the university year, so we say 29th September 2014 (Monday) to 26th January which is around 15 weeks.
Now I'm using something like this:
Date.prototype.getWeek = function() {
var firstJan = new Date(2014,0,1);
var today = new Date(2014, 9, 14);
var firstMonSem1 = new Date(2014, 8, 29);
var firstMonSem2 = new Date(this.getFullYear(), 1, 1);
var dayOfYear = ((today - firstJan + 86400000)/86400000);
var startWeekSem1 = ((firstMonSem1 - firstJan + 86400000)/86400000);
var startWeekSem2 = ((firstMonSem2 - firstJan + 86400000)/86400000);
var currentWeekNumber = Math.ceil(dayOfYear/7);
var startWeekNumberSem1 = Math.ceil(startWeekSem1/7);
var startWeekNumberSem2 = Math.ceil(startWeekSem2/7);
var output = {current: currentWeekNumber, sem1: startWeekNumberSem1, sem2: startWeekNumberSem2};
return output;
};
So i'm returning the current week of the year, semester start date for semester 1 and 2.
But for this example let's only focus on the first is 29th September (Monday) until 26th January which is around 15 weeks.
Now i've worked out based on the values i get when the semester starts and finishes including a 4 week holiday over the christmas period. And then I have an array for the index of which week of the semester we are in, in comparison to the week of the year (this way it could be week 41 in the year and based on the index array I would know that this is week 2).
Here's the code (note: it works!)
var today = new Date();
var info = today.getWeek();
if (info['current'] >= info['sem1'] && info['current'] <= (info['sem1'] + 18)) {
// Semester 1
var index = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var yearWeeks = [];
var count = 1;
for (var i = info['sem1']; i < (info['sem1'] + 18); i++) {
if (count !== 12 && count !== 13 && count !== 14) {
yearWeeks.push(i);
}
count++;
}
var rightIndex = $.inArray(info['current'], yearWeeks);
var x = 1;
while (x <= 15) {
if (x >= rightIndex) {
var weekOption = $("<option/>", {
"value" : x,
html : "Week "+x
}).appendTo(week);
}
x++;
}
}
So what I do here is append to a select all the weeks that are greater than the current week, so if we are in week 5 then there won't be a week 1,2,3,4 for the sake of this example (it's because in the project we are selecting a week to make a booking on but that's irrelevant).
Now, the problem.
This all works fantastically but there is a major catch, the week changes on Wednesday for example:
Week 1 is commencing 29th of September (Monday)
Week 2 starts 8th October (Wednesday)
Week 3 starts 15th October (Wednesday)
So every time the week changes on the Wednesday, now as the idea is that this system is being implemented so you can book room for that given week aka Monday - Friday, I need the weeks to update every Monday rather than Wednesday.
I really need help with this, and I know it might be a lot to grasp. However, I appreciate all the help I can get.
Thank you.

I think you need to replace this line:
var currentWeekNumber = Math.ceil(dayOfYear/7);
To be:
var currentWeekNumber = Math.ceil((dayOfYear + 5)/7);
To make a week start from Wednesday. In such case, the week of Day 2 (Tuesday) is Math.ceil((2+5)/7)=1, while Day 3 (Wednesday) is Math.ceil((3+5)/7)=2.

I worked it out some and hope it helps. This is not just for 2014 that you use, but for the current year. With some adaptation you can adjust.
You get the first of the year and get the offset of the day-number. Then you calculate the current day and subtract. The result will help you get the weeknr.
The week starts on Monday (where in other regions it may be on Sunday).
I created a fiddle, so you can play with it:
http://jsfiddle.net/djwave28/r0m4sokv/
This is an abstract from that fiddle:
// set an offset
var offset = 0;
var now = new Date();
var testday = new Date(now.getTime() + offset * 24 * 60 * 60 * 1000);
var firstofyear = new Date(testday.getFullYear(), 0, 1);
var firstdayoffset = firstofyear.getDay();
var daynr = Math.ceil((testday - firstofyear) / 86400000);
var weeknr = (daynr - firstdayoffset) / 7;

Related

Momentjs - Week Numbers When April Is Week One

Using this function in momentjs I can find the week number of the year:
var dt = new Date();
var weekNumber = moment(dt).week();
Can anyone tell me how to set the first week in April as week one, and therefore for week 52 to be the last week in March.
In the documentation I can only see how to adjust the first day of the year (ie Sunday or Monday). I need to do both. Saturday will actually be day one.
Help much appreciated.
You will have to add a custom function,
Sample
function getCustomWeekNumber(weekNo) {
var baseWeek = moment("01/04/", "DD/MM/").week() - 1; // 13
var lastWeek = moment("31/12/", "DD/MM/").week() //53;
return weekNo > baseWeek ? weekNo - baseWeek : (lastWeek - baseWeek) + weekNo;
}
var d = moment().week();
console.log(getCustomWeekNumber(d))
d = moment("01/04/2016", "DD/MM/YYYY").week();
console.log(getCustomWeekNumber(d))
d = moment("24/03/2016", "DD/MM/YYYY").week();
console.log(getCustomWeekNumber(d))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.0/moment.min.js"></script>

Moment.js how to get week of month? (google calendar style)

I am using Moment.js and it is great. The problem I have now is that I can't figure out how to get the week of the month a certain date is. I can only find "week of year" in the Moment js docs. For example, if I choose today's date (2/12/2014), I would like to know that this date is in the second week of this month of february and consequently, it is the second wednesday of the month. Any ideas?
EDIT:
I guess some clarification is necessary. What I need most is the nth number of a certain day in a month. For example, (from the comments) Feb 1, 2014 would be the first Saturday of the month. Feb 3, 2014 would be the first Monday of the month even though it is "technically" the second week of the month. Basically, exactly how google calendar's repeat function classifies days.
It seems that moment.js does not have the method that implements the functionality that you are looking for.
However, you can find the nth number of a certain day of the week in a month is using the Math.ceil of the date / 7
For example:
var firstFeb2014 = moment("2014-02-01"); //saturday
var day = firstFeb2014.day(); //6 = saturday
var nthOfMoth = Math.ceil(firstFeb2014.date() / 7); //1
var eightFeb2014 = moment("2014-02-08"); //saturday, the next one
console.log( Math.ceil(eightFeb2014.date() / 7) ); //prints 2, as expected
It looks like this is the number you are looking for, as demonstrated by the following test
function test(mJsDate){
var str = mJsDate.toLocaleString().substring(0, 3) +
" number " + Math.ceil(mJsDate.date() / 7) +
" of the month";
return str;
}
for(var i = 1; i <= 31; i++) {
var dayStr = "2014-01-"+ i;
console.log(dayStr + " " + test(moment(dayStr)) );
}
//examples from the console:
//2014-01-8 Wed number 2 of the month
//2014-01-13 Mon number 2 of the month
//2014-01-20 Mon number 3 of the month
//2014-01-27 Mon number 4 of the month
//2014-01-29 Wed number 5 of the month
When calculating the week of the month based on a given date, you have to take the offset into account. Not all months start on the first day of the week.
If you want to take this offset into account, you can use something something like the following if you are using moment.
function weekOfMonth (input = moment()) {
const firstDayOfMonth = input.clone().startOf('month');
const firstDayOfWeek = firstDayOfMonth.clone().startOf('week');
const offset = firstDayOfMonth.diff(firstDayOfWeek, 'days');
return Math.ceil((input.date() + offset) / 7);
}
Simple using moment.js
function week_of_month(date) {
prefixes = [1,2,3,4,5];
return prefixes[0 | moment(date).date() / 7]
}
This library adds the function moment.weekMonth()
https://github.com/c-trimm/moment-recur
I made some modifications based on feedback.
let weeks = moment().weeks() - moment().startOf('month').weeks() + 1;
weeks = (weeks + 52) % 52;
On days passing through the next year, the week value will be negative so I had to add 52.
What about something like:
weekOfCurrentMonth = (moment().week() - (moment().month()*4));
This takes the current week of the year, and subtracts it by the 4 times the number of previous months. Which should give you the week of the current month
I think the answer to this question will be helpful, even though it doesn't use moment.js as requested:
Get week of the month
function countWeekdayOccurrencesInMonth(date) {
var m = moment(date),
weekDay = m.day(),
yearDay = m.dayOfYear(),
count = 0;
m.startOf('month');
while (m.dayOfYear() <= yearDay) {
if (m.day() == weekDay) {
count++;
}
m.add('days', 1);
}
return count;
}
There is a problem with #Daniel Earwicker answer.
I was using his function in my application and the while loop was infinite because of the following situation:
I was trying to figure out which week of december (2016) was the day 31.
the first day of december was day 336 of the year. The last day of december was day 366 of the year.
Problem here: When it was day 366 (31 of december, last day of the year) the code added another day to this date. But with another day added it would be day 1 of january of 2017. Therefore the loop never ended.
while (m.dayOfYear() <= yearDay) {
if (m.day() == weekDay) {
count++;
}
m.add('days', 1);
}
I added the following lines to the code so the problem would be fixed:
function countWeekdayOccurrencesInMonth(date) {
var m = moment(date),
weekDay = m.day(),
yearDay = m.dayOfYear(),
year = m.year(),
count = 0;
m.startOf('month');
while (m.dayOfYear() <= yearDay && m.year() == year) {
if (m.day() == weekDay) {
count++;
}
m.add('days', 1);
}
return count;
}
It verifies if it is still in the same year of the date being veryfied
Here's Robin Malfait's solution implemented with the lightweight library date-fns
import {
differenceInDays,
startOfMonth,
startOfWeek,
getDate
} from 'date-fns'
const weekOfMonth = function (date) {
const firstDayOfMonth = startOfMonth(date)
const firstDayOfWeek = startOfWeek(firstDayOfMonth)
const offset = differenceInDays(firstDayOfMonth, firstDayOfWeek)
return Math.ceil((getDate(date) + offset) / 7)
}
export default weekOfMonth
I'd do the following:
let todaysDate = moment(moment.now());
let endOfLastMonth = moment(get(this, 'todaysDate')).startOf('month').subtract(1, 'week');
let weekOfMonth = todaysDate.diff(endOfLastMonth, 'weeks');
That gets todaysDate and the endOfLastMonth and then uses Moment's built-in diff() method to compute the current month's week number.
It's not built-in, but basically you can subtract the week number of the start of the month from the week number of the date in question.
function weekOfMonth(m) {
return m.week() - moment(m).startOf('month').week() + 1;
}
Credit goes to code by original author, give him a star if it helped you.
How about this?
const moment = require("moment");
// Generate Week Number of The Month From Moment Date
function getWeekOfMonth(input = moment()) {
let dayOfInput = input.clone().day(); // Saunday is 0 and Saturday is 6
let diffToNextWeek = 7 - dayOfInput;
let nextWeekStartDate = input.date() + diffToNextWeek;
return Math.ceil((nextWeekStartDate) / 7);
}
Simple code, but has been working for me.
const weekOfTheMonth = (myMomentDate) => {
const startDay = moment(myMomentDate).startOf('week');
const day = parseInt(startDay.format('DD'),10);
if(day > 28){
return 5;
}
if((day > 21) && (day <= 28) ){
return 4;
}
if((day > 14) && (day <= 21) ){
return 3;
}
if((day > 7) && (day <= 14) ){
return 2;
}
return 1;
}

Is there an easy way to find the last date a day of week occurs in the current month

I am trying to display the date of the last Wednesday in the current month... so that it will automatically change to the correct date when the next month occurs. (So instead of having to say: "Performing the last wednesday of every month", I can dymanmically give the actual date.)
For example, I would want the date to show on the webpage as Wednesday, Sept 25th for this month, and then appear as Wednesday, Oct 30th next month.
A bonus additional solution would be if I could get the next month's date to display after the previous date has past. In my above example, when the current date is Sept 26-30 (any date after that last wednesday, but still in the same month).. the date would show the next performance date of Oct 30th.
It would be great if the solution was through html, javascript/jquery or asp.
Thanks,
SunnyOz
It depends on your criteria for "easy". Here's a simple function to do as required, it's 5 lines of working code that can be reduced to 4, but will lose a bit of clarity if that's done:
function lastDayInMonth(dayName, month, year) {
// Day index map - modify to suit whatever you want to pass to the function
var dayNums = {Sunday: 0, Monday:1, Tuesday:2, Wednesday:3,
Thursday:4, Friday:5, Saturday:6};
// Create a date object for last day of month
var d = new Date(year, month, 0);
// Get day index, make Sunday 7 (could be combined with following line)
var day = d.getDay() || 7;
// Adjust to required day
d.setDate(d.getDate() - (7 - dayNums[dayName] + day) % 7);
return d;
}
You can change the map to whatever, just determine what you want to pass to the function (day name, abbreviation, index, whatever) that can be mapped to an ECMAScript day number.
Edit
So in the case of always wanting to show the last Wednesday of the month or next month if it's passed:
function showLastWed() {
var now = new Date();
var lastWedOfThisMonth = lastDayInMonth('Wednesday', now.getMonth()+1, now.getFullYear());
if (now.getDate() > lastWedOfThisMonth().getDate()) {
return lastDayInMonth('Wednesday', now.getMonth()+2, now.getFullYear());
} else {
return lastWedOfThisMonth;
}
}
Note that the function expects the calendar month number (Jan = 1, Feb = 2, etc.) whereas the getMonth method returns the ECMAScript month index (Jan = 0, Feb = 1, etc.) hence the +1 and +2 to get the calendar month number.
You could use a javascript library such as moment.js:
http://momentjs.com/
and then get it with this:
moment().add('months', 1).date(1).subtract('days', 1).day(-4)
Here is an approach in JS:
var monthLengths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
function getLastWednesday() {
var d = new Date();
var month = d.getMonth();
var lastDay = monthLengths[month];
// mind leap years
if (month == 1) {
var year = d.getFullYear();
var isLeapYear = ((year % 4 == 0 && year % 100 > 0) || year % 400 == 0);
if (isLeapYear) lastDay++;
}
// get the weekday of last day in the curent mont
d.setDate(lastDay);
var weekday = d.getDay();
// calculate return value (wednesday is day 3)
if (weekday == 3) {
return lastDay;
}
else {
var offset = weekday - 3;
if (offset < 0) offset += 7;
return lastDay - offset;
}
}
I prefer to use an abstraction like moment.js as #Aralo suggested. To do it in raw JavaScript, however, you can use some code like this... create a function that gets all the days in a month. Then reverse-traverse the list to find the last day number. Wednesday is 3.
function getDaysInMonth(date) {
var dayCursor = new Date(today.getFullYear(), today.getMonth()); // first day of month
var daysInMonth = [];
while(dayCursor.getMonth() == date.getMonth()) {
daysInMonth.push(new Date(dayCursor));
dayCursor.setDate(dayCursor.getDate() + 1);
}
return daysInMonth;
}
function findLastDay(date, dayNumber) {
var daysInMonth = getDaysInMonth(date);
for(var i = daysInMonth.length - 1; i >= 0; i--) {
var day = daysInMonth[i];
if(day.getDay() === dayNumber) return day;
}
}
Then, to get the last Wednesday in the current month:
var today = new Date();
var lastWednesday = findLastDay(today, 3);

How to get the 7 days in a week with a currentDate in javascript?

(first, sorry for my bad english, i'm a beginner)
I have a chart of percent by date. I would like to display every day of the current week in the x-axis.
So, i tried to find how to get the seven days of the week.
that's what i have :
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();//to set first day on monday, not on sunday, first+1 :
var firstday = (new Date(curr.setDate(first+1))).toString();
for(var i = 1;i<7;i++){
var next = first + i;
var nextday = (new Date(curr.setDate(next))).toString();
alert(nextday);
}
the alert begins well...until the end of the month. That's what i got :
1 : "Mon 27 Feb 2012 ..."
2 : "Tue 28 Feb 2012 ..."
3 : "Wed 29 Feb 2012 ..."
4 : "Thu 01 Mar 2012 ..."
5 : "Sat 31 Mar 2012 ..."
6 : "Sun 01 Apr 2012 ..."
So, as you can see, it switches the friday and... strangely it switch to the good date...4 weeks later...
So, do you have a better solution for me, or maybe you could just help me and say what is the problem.
Thank you!
I'm afraid you have fallen into one of the numerous traps of object mutation. :)
The problem is that, in the line "var nextday = ...", you are changing the date saved in "curr" on every iteration by calling setDate(). That is no problem as long as next is within the range of the current month; curr.setDate(next) is equivalent to going forward one in this case.
The problems begin when next reaches 30. There is no February 30, so setDate() wraps around to the next month, yielding the 1st of March - so far so good. Unfortunately, the next iteration calls curr.setDate(31), and as curr is the 1st of March (remember that the object referenced by curr is changed in each iteration), we get... March 31! The other strange values can be explained the same way.
A way to fix this is to copy curr on each iteration and then call setDate(), like so:
for (var i = 1; i < 7; i++) {
var next = new Date(curr.getTime());
next.setDate(first + i);
alert(next.toString());
}
Thank you all,
I understood that everytime i change the curr value and that was the problem.
All your solutions are working, but i'll prefer the simplest one, the one from #denisw, which I copy there for anybody else with the same problem :
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();
var firstday = (new Date(curr.setDate(first+1))).toString();
for(var i = 1; i < 7; i++) {
var next = new Date(curr.getTime());
next.setDate(first+i);
alert(next.toString());
}
Once again, thank you all, for your quick answers and your help!
You can add date and day. The former goes from 1 to 28..31 and the latter from 0 to 6. What should the Date type do if you set the date to -3?
The solution is to convert all values to milliseconds.
var ONE_DAY_IN_MILLIS = 1000*60*60*24;
var curr = new Date();
// Get offset to first day of week
// Note: Depending on your locale, 0 can be Sunday or Monday.
var offset = curr.getDay() * ONE_DAY_IN_MILLIS;
// Date at the start of week; note that hours, minutes and seconds are != 0
var start = new Date( curr.getTime() - offset );
for( var i=0; i<7; i++ ) {
var nextDay = new Date( start.getTime() + ( i * ONE_DAY_IN_MILLIS ) );
...
}
The problem is that you are modifying your curr date and creating a new date at the same time. There are two ways to do this:
Either never modifiy your curr date object and create new Dates:
var msInDay = 1000 * 60 * 60 * 24;
function addDays(date, days) {
return new Date(date.getTime() + days * msInDay);
}
var curr = new Date();
var first = addDays(curr, -curr.getDay() + 1);
alert(first);
for(var i = 1; i<7; i++) {
var next = addDays(first, i);
alert(next);
}
Or modify your curr date object consistently:
var curr = new Date();
curr.setDate(curr.getDate() - curr.getDay() + 1);
alert(curr);
for(var i = 1; i<7; i++) {
curr.setDate(curr.getDate() + 1);
alert(curr);
}
​
let curr = new Date;
let week = []
for (let i = 1; i <= 7; i++) {
let first = curr.getDate() - curr.getDay() + i
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10)
week.push(day)
}
console.log('week:', week);
jsfidde: https://jsfiddle.net/sinh_nguyen/v9kszn2h/4/

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.
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>
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.
If you don't use jQuery-UI and have no intention of adding the dependency. You could just copy their iso8601Week() implementation since it is written in pure JavaScript without complex dependencies:
// Determine the week of the year (local timezone) based on the ISO 8601 definition.
Date.prototype.iso8601Week = function () {
// Create a copy of the current date, we don't want to mutate the original
const date = new Date(this.getTime());
// Find Thursday of this week starting on Monday
date.setDate(date.getDate() + 4 - (date.getDay() || 7));
const thursday = date.getTime();
// Find January 1st
date.setMonth(0); // January
date.setDate(1); // 1st
const jan1st = date.getTime();
// Round the amount of days to compensate for daylight saving time
const days = Math.round((thursday - jan1st) / 86400000); // 1 day = 86400000 ms
return Math.floor(days / 7) + 1;
};
console.log(new Date().iso8601Week());
console.log(new Date("2020-01-01T00:00").iso8601Week());
console.log(new Date("2021-01-01T00:00").iso8601Week());
console.log(new Date("2022-01-01T00:00").iso8601Week());
console.log(new Date("2023-12-31T00:00").iso8601Week());
console.log(new Date("2024-12-31T00:00").iso8601Week());
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)
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/
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 already use Angular, then you could profit $filter('date').
For example:
var myDate = new Date();
var myWeek = $filter('date')(myDate, 'ww');
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.
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;
};
I was coding in the dark (a challenge) and couldn't lookup, bring in any dependencies 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 instead.
var elm = document.createElement('input')
elm.type = 'week'
elm.valueAsDate = new Date()
var week = elm.value.split('W').pop()
console.log(week)
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.
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)
You could find this fiddle useful. Just finished.
https://jsfiddle.net/dnviti/ogpt920w/
Code below also:
/**
* Get the ISO week date week number
*/
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;
// ISO 8601 states that week 1 is the week
// with the first thursday of that year.
// Set the target date to the thursday in the target week
target.setDate(target.getDate() - dayNr + 3);
// Store the millisecond value of the target date
var firstThursday = target.valueOf();
// Set the target to the first thursday of the year
// First set the target to january first
target.setMonth(0, 1);
// Not a thursday? Correct the date to the next thursday
if (target.getDay() != 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
// The weeknumber is the number of weeks between the
// first thursday of the year and the thursday in the target week
return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000
}
/**
* Get the ISO week date year number
*/
Date.prototype.getWeekYear = function ()
{
// Create a new date object for the thursday of this week
var target = new Date(this.valueOf());
target.setDate(target.getDate() - ((this.getDay() + 6) % 7) + 3);
return target.getFullYear();
}
/**
* Convert ISO week number and year into date (first day of week)
*/
var getDateFromISOWeek = function(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;
}
var printDate = function(){
/*var dateString = document.getElementById("date").value;
var dateArray = dateString.split("/");*/ // use this if you have year-week in the same field
var dateInput = document.getElementById("date").value;
if (dateInput == ""){
var date = new Date(); // get today date object
}
else{
var date = new Date(dateInput); // get date from field
}
var day = ("0" + date.getDate()).slice(-2); // get today day
var month = ("0" + (date.getMonth() + 1)).slice(-2); // get today month
var fullDate = date.getFullYear()+"-"+(month)+"-"+(day) ; // get full date
var year = date.getFullYear();
var week = ("0" + (date.getWeek())).slice(-2);
var locale= "it-it";
document.getElementById("date").value = fullDate; // set input field
document.getElementById("year").value = year;
document.getElementById("week").value = week; // this prototype has been written above
var fromISODate = getDateFromISOWeek(week, year);
var fromISODay = ("0" + fromISODate.getDate()).slice(-2);
var fromISOMonth = ("0" + (fromISODate.getMonth() + 1)).slice(-2);
var fromISOYear = date.getFullYear();
// Use long to return month like "December" or short for "Dec"
//var monthComplete = fullDate.toLocaleString(locale, { month: "long" });
var formattedDate = fromISODay + "-" + fromISOMonth + "-" + fromISOYear;
var element = document.getElementById("fullDate");
element.value = formattedDate;
}
printDate();
document.getElementById("convertToDate").addEventListener("click", printDate);
*{
font-family: consolas
}
<label for="date">Date</label>
<input type="date" name="date" id="date" style="width:130px;text-align:center" value="" />
<br /><br />
<label for="year">Year</label>
<input type="year" name="year" id="year" style="width:40px;text-align:center" value="" />
-
<label for="week">Week</label>
<input type="text" id="week" style="width:25px;text-align:center" value="" />
<br /><br />
<label for="fullDate">Full Date</label>
<input type="text" id="fullDate" name="fullDate" style="width:80px;text-align:center" value="" />
<br /><br />
<button id="convertToDate">
Convert Date
</button>
It's pure JS.
There are a bunch of date functions inside that allow you to convert date into week number and viceversa :)
Luxon is an other alternative. Luxon date objects have a weekNumber property:
let week = luxon.DateTime.fromString("2022-04-01", "yyyy-MM-dd").weekNumber;
console.log(week);
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js"></script>
I've tried using code from all of the answers above, and all return week #52 for the first of January. So I decided to write my own, which calculates the week number correctly.
Week numeration starts from 0
Maybe it's a bad taste to use a loop, or the result can be cached somewhere to prevent repeating the same calculations if the function is called often enough. Well, I have made this for myself, and it does what I need it to do.
Date.prototype.getWeek = function() {
// debugger
let msWeek = 604800000; // Week in milliseconds
let msDay = 86400000; // Day in milliseconds
let year = this.getFullYear(); // Get the year
//let month = this.getMonth(); // Month
let oneDate = new Date(year, 0, 1); // Create a new date based on THIS year
let temp = oneDate.getDay(); // Ordinal of the first day
let getFirstDay = (temp === 0) ? 6 : temp - 1; // Ordinal of the first day of the current month (0-MO, 6-SU)
let countWeek = 0;
// Test to confirm week
oneDate = new Date(oneDate.getTime() + msDay*(7 - getFirstDay));
if(oneDate.getTime() > this.getTime()){
return countWeek;
}
// Increment loop
while(true){
oneDate = new Date(oneDate.getTime() + msWeek); // Add a week and check
if(oneDate.getTime() > this.getTime()) break;
countWeek++;
}
return countWeek + 1;
}
let s1 = new Date('2022-01-01'); console.log(s1.getWeek());
let s2 = new Date('2023-01-01'); console.log(s2.getWeek());
let s22 = new Date('2023-01-02'); console.log(s22.getWeek());
let s3 = new Date('2024-01-01'); console.log(s3.getWeek());
let s4 = new Date('2025-01-01'); console.log(s4.getWeek());
let s5 = new Date('2022-02-28'); console.log(s5.getWeek());
let s6 = new Date('2022-12-31'); console.log(s6.getWeek());
let s7 = new Date('2024-12-31'); console.log(s7.getWeek());
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);
}
};
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.

Categories

Resources