start week day from sunday - javascript - javascript

I want to retrieve a date by providing day number of a specific week
E.g
When I say
day: 1
It should provide me:
2023-01-15
What I have tried so far is:
function calculatedDate (day){
let date = new Date();
let dayAtDate = date.getDay();
let dayDiff = day - dayAtDate;
if(dayDiff < 0){
dayDiff = 7 + dayDiff;
}
let desiredDate = date.setDate(date.getDate() + dayDiff);
return new Date(desiredDate);
}
console.log(calculatedDate(1));
Now the problem with above code is that it considers day: 1 as monday, but I want day: 1 to be sunday here.
Can anyone help me with the best possible way here?

How about just -1 the provided day? that should solve it:
function calculatedDate (day){
let date = new Date();
let dayAtDate = date.getDay();
day = day - 1;
let dayDiff = day - dayAtDate;
if(dayDiff < 0){
dayDiff = 7 + dayDiff;
}
let desiredDate = date.setDate(date.getDate() + dayDiff);
return new Date(desiredDate);
}
console.log(calculatedDate(1));
You'd probably want to add some validation on the input parameter day, make sure it's a number and 1 or greater.

The current day will be 0, account for this by making the following change.
if(dayDiff < 0){
dayDiff = 6 + dayDiff;
}

Sunday is 0, Monday is 1 here :
function calculatedDate (day) {
let date = new Date();
let dayAtDate = date.getDay();
let dayDiff = day - (dayAtDate + 1); // change here
if (dayDiff < 0) {
dayDiff = 7 + dayDiff;
}
let desiredDate = date.setDate(date.getDate() + dayDiff);
return new Date(desiredDate);
}
console.log(calculatedDate(1));

Related

Add days but skip weekends

I have a small problem. I have a working code for adding days depending on the current time (if it is before 10am it adds 1 day if it is after 10am it adds 2 days for the date). So here is my question: How can I edit the code so it will skip the weekends in the calculations? For example, if I execute it before 10am on Friday it should show me the Monday date, not Saturday or Sunday.
function onGetMultiValue() {
var dzis = new Date();
var Godzina = new Date().getHours();
var teraz = dzis.getDate();
if (Godzina < 10) {
dzis.setDate(dzis.getDate() + 1);
} else {
dzis.setDate(dzis.getDate() + 2);
}
var day = dzis.getDate();
var month = dzis.getMonth() + 1;
var year = dzis.getFullYear();
var praca = day+"."+month+"."+year;
return praca;
}
You can use getDay() to check which day of the week it is.
function onGetMultiValue() {
const today = new Date();
const hour = new Date().getHours();
const dayOfWeek = today.getDay();
if (dayOfWeek == 5) {
// if it's Friday add 3 days to the date
today.setDate(today.getDate() + 3);
}
today.setDate(today.getDate() + hour < 10 ? 1 : 2)
const day = today.getDate();
const month = today.getMonth() + 1;
const year = today.getFullYear();
return `${day}.${month}.${year}`;
}
console.log(onGetMultiValue())

How to calculate the elapsed days between two dates

Suppose users trip start from 07/06/2019 and its end on 14/07/2019.
so on 07/06/2019 day will be = 1 (today is 1 day of your trip)
on 08/06/2019 day will be =2 (today is second of your trip)
. so on
I try to do somthing like this but its not working.
let startDay =moment('9.6.2019', 'DD.MM.YYYY')
let today =moment()
let endDay = moment('10.6.2019', 'DD.MM.YYYY')
let start_to_today_days = today.diff(startDay, 'days')
let start_to_end_days = endDay.diff(startDay, 'days')
let actDay = parseInt(start_to_end_days)-
parseInt(start_to_today_days)
let expendday = parseInt(start_to_today_days) - parseInt(actDay)
console.log(Math.abs(expendday))
user booked trip today for 7/06/2019 to 14/07/2109. day counter will start from tomorrow and count elapsed days until end date reached.
You could create a function using moment.js to calculate elapsed times.
// Day of trip is the trip duration + 1..
function getDayOfTrip(tripStartString, currentDateString) {
let startDate = moment(tripStartString, 'DD.MM.YYYY');
let currentDate = moment(currentDateString, 'DD.MM.YYYY');
return currentDate.diff(startDate, 'days') + 1;
}
let tripStartTime = '7.6.2019';
let tripDates = ['7.6.2019', '8.6.2019', '9.6.2019', '10.6.2019', '11.6.2019', '12.6.2019'];
tripDates.forEach(tripDate => console.log(`Trip date: ${tripDate}, day of trip: ${getDayOfTrip(tripStartTime, tripDate)}`));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.25/moment-timezone-with-data-10-year-range.js"></script>
The diff between 2 days will give you the number of milliseconds and with the bellow calculation you can get the number of days:
let startDay =moment('9.6.2019', 'DD.MM.YYYY')
let today =moment()
let endDay = moment('10.6.2019', 'DD.MM.YYYY')
let days = Math.floor(parseInt(endDay - startDay)/(24*60*60*1000));
console.log(Math.abs(days))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
Use below function code to find out no of days elapsed between two dates
function dayElapsed(firstDate , secondDate) {
let day , month , year;
const firstArr = firstDate.split('.');
const secondArr = secondDate.split('.');
day = Math.abs(parseInt(firstArr[0]) - parseInt(secondArr[0]));
month = Math.abs(parseInt(firstArr[1]) - parseInt(secondArr[1]));
year = Math.abs(parseInt(firstArr[2]) - parseInt(secondArr[2]));
return (day + month*30 + year*365);
}
// call to function
dayElapsed('06.06.2019' , '08.06.2019')
I believe that Javascript has a built in Date.
let start = new Date(2019, 5, 7); // (year, month - 1, day)
let end = new Date(2019, 6, 14);
let diff = end - start; // diff is milliseconds
let day = diff / 86400000; // 86400000: milliseconds per day
fixed
tripElapsedDaysOutLayCounter(s, e) {
const COMING_SOON = "COMING SOON",
TRIP_COMPLETED = "TRIP COMPLETED",
INVALID_DATES = "INVALID DATES",
DAY_ONE = 1
let today = moment(new Date().toISOString().slice(0, 10).replace(/-/g, "."), 'YYYY.MM.DD')
let startDay = moment(s, 'YYYY.MM.DD')
let endDay = moment(e, 'YYYY.MM.DD')
let end_start_day = endDay.diff(startDay, 'days')
let today_to_end_day = today.diff(endDay, 'days')
if (startDay.isValid() && endDay.isValid()) {
if (startDay.isAfter(today) && endDay.isAfter(today)) {
return COMING_SOON
} else if (startDay.isBefore(today) && endDay.isBefore(today)) {
return TRIP_COMPLETED
} else if (startDay.isSame(today) && endDay.isAfter(today)) {
return DAY_ONE
} else if (startDay.isSame(endDay)) {
return DAY_ONE
} else {
return Math.abs(Math.abs(end_start_day) -
Math.abs(today_to_end_day))+1
}
} else {
return INVALID_DATES
}
}
Thank you everyone for your precious answers

group by weeks,days and year javascript [duplicate]

I have today = new Date(); object. I need to get first and last day of the current week. I need both variants for Sunday and Monday as a start and end day of the week. I am little bit confuse now with a code. Can your help me?
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
firstday
"Sun, 06 Mar 2011 12:25:40 GMT"
lastday
"Sat, 12 Mar 2011 12:25:40 GMT"
This works for firstday = sunday of this week and last day = saturday for this week. Extending it to run Monday to sunday is trivial.
Making it work with first and last days in different months is left as an exercise for the user
Be careful with the accepted answer, it does not set the time to 00:00:00 and 23:59:59, so you can have problems.
You can use a third party date library to deal with dates. For example:
var startOfWeek = moment().startOf('week').toDate();
var endOfWeek = moment().endOf('week').toDate();
EDIT: As of September 2020, using Moment is discouraged for new projects (blog post)
Another popular alternative is date-fns.
You can also use following lines of code to get first and last date of the week:
var curr = new Date;
var firstday = new Date(curr.setDate(curr.getDate() - curr.getDay()));
var lastday = new Date(curr.setDate(curr.getDate() - curr.getDay()+6));
Hope it will be useful..
The excellent (and immutable) date-fns library handles this most concisely:
const start = startOfWeek(date);
const end = endOfWeek(date);
Default start day of the week is Sunday (0), but it can be changed to Monday (1) like this:
const start = startOfWeek(date, {weekStartsOn: 1});
const end = endOfWeek(date, {weekStartsOn: 1});
Here's a quick way to get first and last day, for any start day.
knowing that:
1 day = 86,400,000 milliseconds.
JS dates values are in milliseconds
Recipe: figure out how many days you need to remove to get the your week's start day (multiply by 1 day's worth of milliseconds). All that is left after that is to add 6 days to get your end day.
var startDay = 1; //0=sunday, 1=monday etc.
var d = now.getDay(); //get the current day
var weekStart = new Date(now.valueOf() - (d<=0 ? 7-startDay:d-startDay)*86400000); //rewind to start day
var weekEnd = new Date(weekStart.valueOf() + 6*86400000); //add 6 days to get last day
Small change to #Chris Lang answer.
if you want Monday as the first day use this.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay()+ (this.getDay() == 0 ? -6:1) )));
}
Date.prototype.GetLastDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay() +7)));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
Thaks #Chris Lang
This works across year and month changes.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay())));
}
Date.prototype.GetLastDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay() +6)));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
You could do something like this
var today = new Date();
var startDay = 0;
var weekStart = new Date(today.getDate() - (7 + today.getDay() - startDay) % 7);
var weekEnd = new Date(today.getDate() + (7 - today.getDay() - startDay) % 7);
Where startDay is a number from 0 to 6 where 0 stands for Sunday (ie 1 = Monday, 2 = Tuesday, etc).
SetDate will sets the day of the month. Using setDate during start and end of the month,will result in wrong week
var curr = new Date("08-Jul-2014"); // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)); // 06-Jul-2014
var lastday = new Date(curr.setDate(last)); //12-Jul-2014
If u setting Date is 01-Jul-2014, it will show firstday as 29-Jun-2014 and lastday as 05-Jun-2014 instead of 05-Jul-2014
So overcome this issue i used
var curr = new Date();
day = curr.getDay();
firstday = new Date(curr.getTime() - 60*60*24* day*1000); //will return firstday (ie sunday) of the week
lastday = new Date(firstday.getTime() + 60 * 60 *24 * 6 * 1000); //adding (60*60*6*24*1000) means adding six days to the firstday which results in lastday (saturday) of the week
I recommend to use Moment.js for such cases. I had scenarios where I had to check current date time, this week, this month and this quarters date time. Above an answer helped me so I thought to share rest of the functions as well.
Simply to get current date time in specific format
case 'Today':
moment().format("DD/MM/YYYY h:mm A");
case 'This Week':
moment().endOf('isoweek').format("DD/MM/YYYY h:mm A");
Week starts from Sunday and ends on Saturday if we simply use 'week' as parameter for endOf function but to get Sunday as the end of the week we need to use 'isoweek'.
case 'This Month':
moment().endOf('month').format("DD/MM/YYYY h:mm A");
case 'This Quarter':
moment().endOf('quarter').format("DD/MM/YYYY h:mm A");
I chose this format as per my need. You can change the format according to your requirement.
//get start of week; QT
function _getStartOfWeek (date){
var iDayOfWeek = date.getDay();
var iDifference = date.getDate() - iDayOfWeek + (iDayOfWeek === 0 ? -6:1);
return new Date(date.setDate(iDifference));
},
function _getEndOfWeek(date){
return new Date(date.setDate(date.getDate() + (7 - date.getDay()) === 7 ? 0 : (7 - date.getDay()) ));
},
*current date == 30.06.2016 and monday is the first day in week.
It also works for different months and years.
Tested with qunit suite:
QUnit.module("Planung: Start of week");
QUnit.test("Should return start of week based on current date", function (assert) {
var startOfWeek = Planung._getStartOfWeek(new Date());
assert.ok( startOfWeek , "returned date: "+ startOfWeek);
});
QUnit.test("Should return start of week based on a sunday date", function (assert) {
var startOfWeek = Planung._getStartOfWeek(new Date("2016-07-03"));
assert.ok( startOfWeek , "returned date: "+ startOfWeek);
});
QUnit.test("Should return start of week based on a monday date", function (assert) {
var startOfWeek = Planung._getStartOfWeek(new Date("2016-06-27"));
assert.ok( startOfWeek , "returned date: "+ startOfWeek);
});
QUnit.module("Planung: End of week");
QUnit.test("Should return end of week based on current date", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date());
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on sunday date with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-07-03"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on monday date with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-27"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 01-06-2016 with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-01"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 21-06-2016 with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-21"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 28-12-2016 with different month and year", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-12-28"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 01-01-2016 with different month and year", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-01-01"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
var dt = new Date() //current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay-1
var wkStart = new Date(new Date(dt).setDate(dt.getDate()- lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate()+6));
This will be useful for any date scenario.
Just using pure javascript, you can use the function below to get first day and last day of a week with freely setting day for start of week.
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
function getFirstDayOfWeek(date, from) {
//Default start week from 'Sunday'. You can change it yourself.
from = from || 'Sunday';
var index = weekday.indexOf(from);
var start = index >= 0 ? index : 0;
var d = new Date(date);
var day = d.getDay();
var diff = d.getDate() - day + (start > day ? start - 7 : start);
d.setDate(diff);
return d;
};
Last day of week is just 6 days after first day of week
function getLastDayOfWeek(date, from) {
from = from || 'Sunday';
var index = weekday.indexOf(from);
var start = index >= 0 ? index : 0;
var d = new Date(date);
var day = d.getDay();
var diff = d.getDate() - day + (start > day ? start - 1 : 6 + start);
d.setDate(diff);
return d;
};
Test:
getFirstDayOfWeek('2017-10-16'); //--> Sun Oct 15 2017
getFirstDayOfWeek('2017-10-16', 'Monday'); //--> Mon Oct 16 2017
getFirstDayOfWeek('2017-10-16', 'Tuesday'); //--> Tue Oct 10 2017
The biggest issue when the given date's week is in-between two months. (Like 2022-07-01, it's the 5th day of the week.)
Using getDay function we check if the week is in-between months.
Note: getDay() function identifies week start day as sunday, so it'll return 0 for sunday.
var curr = new Date(); // get current date
var weekdaynum = curr.getDay();
if(weekdaynum == 0){ //to change sunday to the last day of the week
weekdaynum = 6;
} else{
weekdaynum = weekdaynum-1;
}
var firstweek = curr.getDate() - weekdaynum;
var lastweek = firstweek + 6; // last day is the first day + 6
if((curr.getDate()-weekdaynum) <= 0){
var firstweek_lasmonth_lastdate = new Date(currweek.getFullYear(),currweek.getMonth(), 0);
var firstweek_diff = firstweek_lasmonth_lastdate.getDate()-Math.abs(firstweek);
var firstweekday = new Date(currweek.getFullYear(),currweek.getMonth()-1,firstweek_lasmonth_lastdate.getDate()+firstweek_diff);
var lastweekday = new Date(currweek.getFullYear(),currweek.getMonth()-1,firstweek_lasmonth_lastdate.getDate()+firstweek_diff+7);
} else{
var firstweekday = new Date(curr.setDate(firstweek));
var lastweekday = new Date(curr.setDate(lastweek));
}
So this will return (given date is: 2022/07/01):
firstweekday = Mon Jun 27 2022 00:00:00
lastweekday = Sun Jul 03 2022 00:00:00
Hope this helps.
krtek's method has some wrong,I tested this
var startDay = 0;
var weekStart = new Date(today.getDate() - (7 + today.getDay() - startDay) % 7);
var weekEnd = new Date(today.getDate() + (6 - today.getDay() - startDay) % 7);
it works
Although the question is seeming as obsolete I have to point out a problem.
Question: What will happen at 1st January 2016?
I think most of the above solutions calculate start of week as 27.12.2016.
For this reason I think, the correct calculation should be like the below simply;
var d = new Date(),
dayInMs = 1000 * 60 * 60 * 24,
weekInMs = dayInMs * 7,
startOfToday = new Date(d.getFullYear(), d.getMonth(), d.getDate()).valueOf(),
todayElapsedTime = d.valueOf() - startOfToday,
dayDiff = d.getDay() * dayInMs,
dateDiff = dayDiff + todayElapsedTime,
// finally
startOfWeek = d.valueOf() - dateDiff,
endOfWeek = startOfWeek + weekInMs - 1;
JavaScript
function getWeekDays(curr, firstDay = 1 /* 0=Sun, 1=Mon, ... */) {
var cd = curr.getDate() - curr.getDay();
var from = new Date(curr.setDate(cd + firstDay));
var to = new Date(curr.setDate(cd + 6 + firstDay));
return {
from,
to,
};
};
TypeScript
export enum WEEK_DAYS {
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
}
export const getWeekDays = (
curr: Date,
firstDay: WEEK_DAYS = WEEK_DAYS.Monday
): { from: Date; to: Date } => {
const cd = curr.getDate() - curr.getDay();
const from = new Date(curr.setDate(cd + firstDay));
const to = new Date(curr.setDate(cd + 6 + firstDay));
return {
from,
to,
};
};
function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
return new Date(d.setDate(diff));
}
console.log( getMonday(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())) ) // Mon Nov 08 2010
Pure vanilla JS. no third party libraries.
const now = new Date()
const startOfWeek = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay())
const endOfWeek = new Date(now.getFullYear(), now.getMonth(), startOfWeek.getDate() + 7)
^ this returns Sunday 00am to Sunday 00am. Adjust the "7" to get what you want.
var currentDate = new Date();
var firstday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay())).toUTCString();
var lastday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 6)).toUTCString();
console.log("firstday", firstday);
console.log("lastday", lastday);
Works with different months and years.
let wDate = new Date();
let dDay = wDate.getDay() > 0 ? wDate.getDay() : 7;
let first = wDate.getDate() - dDay + 1;
let firstDayWeek = new Date(wDate.setDate(first));
let lastDayWeek = new Date(wDate.setDate(firstDayWeek.getDate()+6));
console.log(firstDayWeek.toLocaleDateString());
console.log(lastDayWeek.toLocaleDateString());
Nice suggestion but you got a small problem in lastday.
You should change it to:
lastday = new Date(firstday.getTime() + 60 * 60 *24 * 6 * 1000);
The moment approach worked for me for all the cases ( although i have not test the boundaries like year end , leap years ). Only Correction in the above code is the parameter is "isoWeek" , if you want to start the week from Monday.
let startOfWeek = moment().startOf("isoWeek").toDate();
let endOfWeek = moment().endOf("isoWeek").toDate();
We have added jquery code that shows the current week of days from monday to sunday.
var d = new Date();
var week = [];
var _days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var _months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
for (let i = 1; i <= 7; i++) {
let first = d.getDate() - d.getDay() + i;
let dt = new Date(d.setDate(first));
var _day = _days[dt.getDay()];
var _month = _months[dt.getMonth()];
var _date = dt.getDate();
if(_date < 10 ){
_date = '0' +_date;
}
var _year = dt.getFullYear();
var fulldate = _day+' '+_month+' '+_date+' '+_year+' ';
week.push(fulldate);
}
console.log(week);
An old question with lots of answers, so another one won't be an issue. Some general functions to get the start and end of all sorts of time units.
For startOf and endOf week, the start day of the week defaults to Sunday (0) but any day can be passed (Monday - 1, Tuesday - 2, etc.). Only uses Gregorian calendar though.
The functions don't mutate the source date, so to see if a date is in the same week as some other date (week starting on Monday):
if (d >= startOf('week', d1, 1) && d <= endOf('week', d1, 1)) {
// d is in same week as d1
}
or in the current week starting on Sunday:
if (d >= startOf('week') && d <= endOf('week')) {
// d is in the current week
}
// Returns a new Date object set to start of given unit
// For start of week, accepts any day as start
function startOf(unit, date = new Date(), weekStartDay = 0) {
// Copy original so don't modify it
let d = new Date(date);
let e = new Date(d);
e.setHours(23,59,59,999);
// Define methods
let start = {
second: d => d.setMilliseconds(0),
minute: d => d.setSeconds(0,0),
hour : d => d.setMinutes(0,0,0),
day : d => d.setHours(0,0,0,0),
week : d => {
start.day(d);
d.setDate(d.getDate() - d.getDay() + weekStartDay);
if (d > e) d.setDate(d.getDate() - 7);
},
month : d => {
start.day(d);
d.setDate(1);
},
year : d => {
start.day(d);
d.setMonth(0, 1);
},
decade: d => {
start.year(d);
let year = d.getFullYear();
d.setFullYear(year - year % 10);
},
century: d => {
start.year(d);
let year = d.getFullYear();
d.setFullYear(year - year % 100);
},
millenium: d => {
start.year(d);
let year = d.getFullYear();
d.setFullYear(year - year % 1000);
}
}
start[unit](d);
return d;
}
// Returns a new Date object set to end of given unit
// For end of week, accepts any day as start day
// Requires startOf
function endOf(unit, date = new Date(), weekStartDay = 0) {
// Copy original so don't modify it
let d = new Date(date);
let e = new Date(date);
e.setHours(23,59,59,999);
// Define methods
let end = {
second: d => d.setMilliseconds(999),
minute: d => d.setSeconds(59,999),
hour : d => d.setMinutes(59,59,999),
day : d => d.setHours(23,59,59,999),
week : w => {
w = startOf('week', w, weekStartDay);
w.setDate(w.getDate() + 6);
end.day(w);
d = w;
},
month : d => {
d.setMonth(d.getMonth() + 1, 0);
end.day(d);
},
year : d => {
d.setMonth(11, 31);
end.day(d);
},
decade: d => {
end.year(d);
let y = d.getFullYear();
d.setFullYear(y - y % 10 + 9);
},
century: d => {
end.year(d);
let y = d.getFullYear();
d.setFullYear(y - y % 100 + 99);
},
millenium: d => {
end.year(d);
let y = d.getFullYear();
d.setFullYear(y - y % 1000 + 999);
}
}
end[unit](d);
return d;
}
// Examples
let d = new Date();
['second','minute','hour','day','week','month','year',
'decade','century','millenium'].forEach(unit => {
console.log(('Start of ' + unit).padEnd(18) + ': ' +
startOf(unit, d).toString());
console.log(('End of ' + unit).padEnd(18) + ': ' +
endOf(unit, d).toString());
});
var currentDate = new Date();
var firstday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay())).toUTCString();
var lastday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 7)).toUTCString();
console.log(firstday, lastday)
I'm using the following code in but because of .toUTCString() i'm receiving the following error as show in image.
if i remove .toUTCString(). output which i receive is not as expected
Small change to #SHIVA's answer which is a changed #Chris Lang answer.
For monday first usage with fix when today is sunday.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay()+ (this.getDay() == 0 ? -6:1) )));
}
Date.prototype.GetLastDayOfWeek = function() {
return new Date(this.setDate(this.getDate() - (this.getDay() == 0 ? 7 : this.getDay()) + 7));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
You can try the below one too
let weekBgnDt = new Date();
let weekEndDt = new Date();
let wBeginDateLng, wEndDateLng, diffDays,dateCols=[];
if (weekBgnDt.getDay() > 0) {
diffDays = 0 - weekBgnDt.getDay();
weekBgnDt.setDate(weekBgnDt.getDate() + diffDays)
}
weekEndDt = weekEndDt.setDate(weekBgnDt.getDate() + 6)
wBeginDate = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: '2-digit' }).format(weekBgnDt);
wEndDate = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric', month:
'2-digit' }).format(weekEndDt);
wBeginDateLng = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: 'long' }).format(weekBgnDt);
wEndDateLng = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: 'long' }).format(weekEndDt);
console.log(wBeginDate, "-", wBeginDateLng)
console.log(wEndDate, "-", wEndDateLng)
for(let i=weekBgnDt;i<=weekEndDt;){
dateCols.push(new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: '2-digit' }).format(i));
i=weekBgnDt.setDate(weekBgnDt.getDate()+1)
}
console.log({wBeginDate,wBeginDateLng,wEndDate,wEndDateLng,dateCols})
The result will be printed as
{ wBeginDate: "16/05/2021", wBeginDateLng: "16 May 2021", wEndDate: "22/05/2021", wEndDateLng: "22 May 2021", dateCols: Array ["16/05/2021", "17/05/2021", "18/05/2021", "19/05/2021", "20/05/2021", "21/05/2021", "22/05/2021"] }
The right way to get the first and last date of the current week with appropriate month & year is as below
const curr = new Date();
const first = curr.getDate() - curr.getDay() + 1; // Start from Monday
const firstDate = new Date(curr.setDate(first));
const lastDate = new Date(curr.setDate(firstDate.getDate() + 6));
console.log(firstDate.toLocaleDateString(), lastDate.toLocaleDateString());
You can use this function, it works with first and last day of the week in different months or years
const getFirstAndLastDayOfTheWeek = () => {
// The starting time is the same current
let a = new Date();
let b = new Date();
const weekDay = a.getDay();
if (weekDay === 0) {
a.setDate(a.getDate() - 6);
} else if (weekDay === 1) {
b.setDate(b.getDate() + 7 - b.getDay());
} else if (weekDay >= 1) {
a.setDate(a.getDate() - a.getDay() + 1);
b.setDate(b.getDate() + 7 - b.getDay());
}
return { firstWeekDate: a, lastWeekDate: b };
}
console.log(getFirstAndLastDayOfTheWeek());

Is there a way that I can get the (first Sunday in October – first Sunday in April) with moment.js?

I know that I can use this for the start of the month moment().startOf('month') but I need the first Sunday of the month.
You could do this:
function getFirstWeekDay(dateString, dayOfWeek) {
var date = moment(dateString, "YYYY-MM-DD");
var day = date.day();
var diffDays = 0;
if (day > dayOfWeek) {
diffDays = 7 - (day - dayOfWeek);
} else {
diffDays = dayOfWeek - day
}
console.log(date.add(diffDays, 'day').format("YYYY-MM-DD"));
}
//Pass in the first of a given calendar month and the day weekday
getFirstWeekDay("2016-10-01", 0);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
Please check this Code.
var d = new Date();
var first_week = d.getDate();
var the_day = d.getDay();
if(first_week <= 7 && the_day == 0)
{
// It's the first Sunday of the month
// Do more stuff here
}
Here is the sample using js to get the first sunday of any month or year
function firstSunday(month, year) {
let tempDate = new Date();
tempDate.setHours(0,0,0,0);
// first SUNDAY of april
tempDate.setMonth(month);
tempDate.setYear(year);
tempDate.setDate(1);
let day = tempDate.getDay();
let toNextSun = day !== 0 ? 7 - day : 0;
tempDate.setDate(tempDate.getDate() + toNextSun);
return tempDate.toDateString();
}
console.log("april first sunday" , firstSunday(3 , 2020));
console.log("oct first sunday" , firstSunday(9 , 2020))

Get Weeks In Month Through Javascript

In Javascript, how do I get the number of weeks in a month? I can't seem to find code for this anywhere.
I need this to be able to know how many rows I need for a given month.
To be more specific, I would like the number of weeks that have at least one day in the week (a week being defined as starting on Sunday and ending on Saturday).
So, for something like this, I would want to know it has 5 weeks:
S M T W R F S
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Thanks for all the help.
Weeks start on Sunday
This ought to work even when February doesn't start on Sunday.
function weekCount(year, month_number) {
// month_number is in the range 1..12
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var used = firstOfMonth.getDay() + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
Weeks start on Monday
function weekCount(year, month_number) {
// month_number is in the range 1..12
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var used = firstOfMonth.getDay() + 6 + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
Weeks start another day
function weekCount(year, month_number, startDayOfWeek) {
// month_number is in the range 1..12
// Get the first day of week week day (0: Sunday, 1: Monday, ...)
var firstDayOfWeek = startDayOfWeek || 0;
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var numberOfDaysInMonth = lastOfMonth.getDate();
var firstWeekDay = (firstOfMonth.getDay() - firstDayOfWeek + 7) % 7;
var used = firstWeekDay + numberOfDaysInMonth;
return Math.ceil( used / 7);
}
None of the solutions proposed here don't works correctly, so I wrote my own variant and it works for any cases.
Simple and working solution:
/**
* Returns count of weeks for year and month
*
* #param {Number} year - full year (2016)
* #param {Number} month_number - month_number is in the range 1..12
* #returns {number}
*/
var weeksCount = function(year, month_number) {
var firstOfMonth = new Date(year, month_number - 1, 1);
var day = firstOfMonth.getDay() || 6;
day = day === 1 ? 0 : day;
if (day) { day-- }
var diff = 7 - day;
var lastOfMonth = new Date(year, month_number, 0);
var lastDate = lastOfMonth.getDate();
if (lastOfMonth.getDay() === 1) {
diff--;
}
var result = Math.ceil((lastDate - diff) / 7);
return result + 1;
};
you can try it here
This is very simple two line code. and i have tested 100%.
Date.prototype.getWeekOfMonth = function () {
var firstDay = new Date(this.setDate(1)).getDay();
var totalDays = new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
return Math.ceil((firstDay + totalDays) / 7);
}
How to use
var totalWeeks = new Date().getWeekOfMonth();
console.log('Total Weeks in the Month are : + totalWeeks );
You'll have to calculate it.
You can do something like
var firstDay = new Date(2010, 0, 1).getDay(); // get the weekday january starts on
var numWeeks = 5 + (firstDay >= 5 ? 1 : 0); // if the months starts on friday, then it will end on sunday
Now we just need to genericize it.
var dayThreshold = [ 5, 1, 5, 6, 5, 6, 5, 5, 6, 5, 6, 5 ];
function GetNumWeeks(month, year)
{
var firstDay = new Date(year, month, 1).getDay();
var baseWeeks = (month == 1 ? 4 : 5); // only February can fit in 4 weeks
// TODO: account for leap years
return baseWeeks + (firstDay >= dayThreshold[month] ? 1 : 0); // add an extra week if the month starts beyond the threshold day.
}
Note: When calling, remember that months are zero indexed in javascript (i.e. January == 0).
function weeksinMonth(m, y){
y= y || new Date().getFullYear();
var d= new Date(y, m, 0);
return Math.floor((d.getDate()- 1)/7)+ 1;
}
alert(weeksinMonth(3))
// the month range for this method is 1 (january)-12(december)
The most easy to understand way is
<div id="demo"></div>
<script type="text/javascript">
function numberOfDays(year, month)
{
var d = new Date(year, month, 0);
return d.getDate();
}
function getMonthWeeks(year, month_number)
{
var $num_of_days = numberOfDays(year, month_number)
, $num_of_weeks = 0
, $start_day_of_week = 0;
for(i=1; i<=$num_of_days; i++)
{
var $day_of_week = new Date(year, month_number, i).getDay();
if($day_of_week==$start_day_of_week)
{
$num_of_weeks++;
}
}
return $num_of_weeks;
}
var d = new Date()
, m = d.getMonth()
, y = d.getFullYear();
document.getElementById('demo').innerHTML = getMonthWeeks(y, m);
</script>
using moment js
function getWeeksInMonth(year, month){
var monthStart = moment().year(year).month(month).date(1);
var monthEnd = moment().year(year).month(month).endOf('month');
var numDaysInMonth = moment().year(year).month(month).endOf('month').date();
//calculate weeks in given month
var weeks = Math.ceil((numDaysInMonth + monthStart.day()) / 7);
var weekRange = [];
var weekStart = moment().year(year).month(month).date(1);
var i=0;
while(i<weeks){
var weekEnd = moment(weekStart);
if(weekEnd.endOf('week').date() <= numDaysInMonth && weekEnd.month() == month) {
weekEnd = weekEnd.endOf('week').format('LL');
}else{
weekEnd = moment(monthEnd);
weekEnd = weekEnd.format('LL')
}
weekRange.push({
'weekStart': weekStart.format('LL'),
'weekEnd': weekEnd
});
weekStart = weekStart.weekday(7);
i++;
}
return weekRange;
} console.log(getWeeksInMonth(2016, 7))
ES6 variant, using consistent zero-based months index. Tested for years from 2015 to 2025.
/**
* Returns number of weeks
*
* #param {Number} year - full year (2018)
* #param {Number} month - zero-based month index (0-11)
* #param {Boolean} fromMonday - false if weeks start from Sunday, true - from Monday.
* #returns {number}
*/
const weeksInMonth = (year, month, fromMonday = false) => {
const first = new Date(year, month, 1);
const last = new Date(year, month + 1, 0);
let dayOfWeek = first.getDay();
if (fromMonday && dayOfWeek === 0) dayOfWeek = 7;
let days = dayOfWeek + last.getDate();
if (fromMonday) days -= 1;
return Math.ceil(days / 7);
}
You could use my time.js library. Here's the weeksInMonth function:
// http://github.com/augustl/time.js/blob/623e44e7a64fdaa3c908debdefaac1618a1ccde4/time.js#L67
weeksInMonth: function(){
var millisecondsInThisMonth = this.clone().endOfMonth().epoch() - this.clone().firstDayInCalendarMonth().epoch();
return Math.ceil(millisecondsInThisMonth / MILLISECONDS_IN_WEEK);
},
It might be a bit obscure since the meat of the functionality is in endOfMonth and firstDayInCalendarMonth, but you should at least be able to get some idea of how it works.
This works for me,
function(d){
var firstDay = new Date(this.getFullYear(), this.getMonth(), 1).getDay();
return Math.ceil((d.getDate() + (firstDay - 1))/7);
}
"d" should be the date.
A little rudimentary, yet should cater for original post :
/**
* #param {date} 2020-01-30
* #return {int} count
*/
this.numberOfCalendarWeekLines = date => {
// get total
let lastDayOfMonth = new Date( new Date( date ).getFullYear(), new Date( date ).getMonth() + 1, 0 );
let manyDaysInMonth = lastDayOfMonth.getDate();
// itterate through month - from 1st
// count calender week lines by occurance
// of a Saturday ( s m t w t f s )
let countCalendarWeekLines = 0;
for ( let i = 1; i <= manyDaysInMonth; i++ ) {
if ( new Date( new Date( date ).setDate( i ) ).getDay() === 6 ) countCalendarWeekLines++;
}
// days after last occurance of Saturday
// leaked onto new line?
if ( lastDayOfMonth.getDay() < 6 ) countCalendarWeekLines++;
return countCalendarWeekLines;
};
Thanks to Ed Poor for his solution, this is the same as Date prototype.
Date.prototype.countWeeksOfMonth = function() {
var year = this.getFullYear();
var month_number = this.getMonth();
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var used = firstOfMonth.getDay() + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
So you can use it like
var weeksInCurrentMonth = new Date().countWeeksOfMonth();
var weeksInDecember2012 = new Date(2012,12,1).countWeeksOfMonth(); // 6
function getWeeksInMonth(month_number, year) {
console.log("year - "+year+" month - "+month_number+1);
var day = 0;
var firstOfMonth = new Date(year, month_number, 1);
var lastOfMonth = new Date(year, parseInt(month_number)+1, 0);
if (firstOfMonth.getDay() == 0) {
day = 2;
firstOfMonth = firstOfMonth.setDate(day);
firstOfMonth = new Date(firstOfMonth);
} else if (firstOfMonth.getDay() != 1) {
day = 9-(firstOfMonth.getDay());
firstOfMonth = firstOfMonth.setDate(day);
firstOfMonth = new Date(firstOfMonth);
}
var days = (lastOfMonth.getDate() - firstOfMonth.getDate())+1
return Math.ceil( days / 7);
}
It worked for me. Please try
Thanks all
This piece of code give you the exact number of weeks in a given month:
Date.prototype.getMonthWeek = function(monthAdjustement)
{
var firstDay = new Date(this.getFullYear(), this.getMonth(), 1).getDay();
var returnMessage = (Math.ceil(this.getDate()/7) + Math.floor(((7-firstDay)/7)));
return returnMessage;
}
The monthAdjustement variable adds or substract the month that you are currently in
I use it in a calendar project in JS and the equivalent in Objective-C and it works well
function weekCount(year, month_number, day_start) {
// month_number is in the range 1..12
// day_start is in the range 0..6 (where Sun=0, Mon=1, ... Sat=6)
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var dayOffset = (firstOfMonth.getDay() - day_start + 7) % 7;
var used = dayOffset + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
I know this is coming late, I have seen codes upon codes trying to get the number of weeks a particular month falls on, but many have not been really precise but most have been really informative and reusable, I'm not an expert programmer but I can really think and thanks to some codes by some people I was able to arrive at a conclusion.
function convertDate(date) {//i lost the guy who owns this code lol
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth()+1).toString();
var dd = date.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}
//this line of code from https://stackoverflow.com/a/4028614/2540911
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var myDate = new Date('2019-03-2');
//var myDate = new Date(); //or todays date
var c = convertDate(myDate).split("-");
let yr = c[0], mth = c[1], dy = c[2];
weekCount(yr, mth, dy)
//Ahh yes, this line of code is from Natim Up there, incredible work, https://stackoverflow.com/a/2485172/2540911
function weekCount(year, month_number, startDayOfWeek) {
// month_number is in the range 1..12
console.log(weekNumber);
// Get the first day of week week day (0: Sunday, 1: Monday, ...)
var firstDayOfWeek = startDayOfWeek || 0;
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var numberOfDaysInMonth = lastOfMonth.getDate();
var first = firstOfMonth.getDate();
//initialize first week
let weekNumber = 1;
while(first-1 < numberOfDaysInMonth){
// add a day
firstOfMonth = firstOfMonth.setDate(firstOfMonth.getDate() + 1);//this line of code from https://stackoverflow.com/a/9989458/2540911
if(days[firstOfMonth.getDay()] === "Sunday"){//get new week every new sunday according the local date format
//get newWeek
weekNumber++;
}
if(weekNumber === 3 && days[firstOfMonth.getDay()] === "Friday")
alert(firstOfMonth);
first++
}
}
I needed this code to generate a schedule or event scheduler for a church on every 3rd friday of a new month, so you can modify this to suit your or just pick your specific date, not "friday and specify the week of the month and Voila!! here you go
None of the solutions here really worked for me. Here is my crack at it.
// Example
// weeksOfMonth(2019, 9) // October
// Result: 5
weeksOfMonth (year, monthIndex) {
const d = new Date(year, monthIndex+ 1, 0)
const adjustedDate = d.getDate() + d.getDay()
return Math.ceil(adjustedDate / 7)
}
Every solutions helped but nothing was working for me so I did my own with moment library :
const getWeeksInAMonth = (currentDate: string) => {
const startOfMonth = moment(currentDate).startOf("month")
const endOfMonth = moment(currentDate).endOf("month")
return moment(endOfMonth).week() - moment(startOfMonth).week() + 1
}

Categories