How to get a specify date in every month in Javascript? - javascript

I need to find this month, previous month and the next month of a specific date.
For example, date was set to 31 of every month, what I expect to get the date is
2018-02-28, 2018-03-31 and 2018-04-30. For those dates which has no 31, than it becomes the day before.
And finally generate 2 period, 2018-02-28 to 2018-03-29, 2018-03-30 to 2018-04-31.
I don't know how to handle feb and the month which less than 31.
var d = new Date();
var tyear = d.getFullYear(); //2018
var tmonth = d.getMonth(); //2
new Date(2018, tmonth-1, 31);//output 2018-03-02 not what I wanted

A simple algorithm is to add months to the original date, and if the new date is wrong, set it to the last day of the previous month. Keeping the original date values unmodified helps, e.g.
/* #param {Date} start - date to start
** #param {number} count - number of months to generate dates for
** #returns {Array} monthly Dates from start for count months
*/
function getMonthlyDates(start, count) {
var result = [];
var temp;
var year = start.getFullYear();
var month = start.getMonth();
var startDay = start.getDate();
for (var i=0; i<count; i++) {
temp = new Date(year, month + i, startDay);
if (temp.getDate() != startDay) temp.setDate(0);
result.push(temp);
}
return result;
}
// Start on 31 Jan in leap year
getMonthlyDates(new Date(2016,0,31), 4).forEach(d => console.log(d.toString()));
// Start on 31 Jan not in leap year
getMonthlyDates(new Date(2018,0,31), 4).forEach(d => console.log(d.toString()));
// Start on 30 Jan
getMonthlyDates(new Date(2018,0,30), 4).forEach(d => console.log(d.toString()));
// Start on 5 Jan
getMonthlyDates(new Date(2018,0,5), 4).forEach(d => console.log(d.toString()));

I think you're going to need an array with 12 numbers in it. Each number is the amount of days in each month and the numbers in the array go in order (first number is 31 because January has 31 days, second is 28 or 29 for Feb), etc. Then you'll get the month number from your input date and look in the array at the number corresponding to the month number +/- 1.
You'll then need to construct a date for the previous month and the next month based on the number of days in the current month.
See comments inline:
let daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
document.getElementById("date").addEventListener("input", function(){
console.clear();
// Create new Date based on value in date picker
var selectedDate = new Date(this.value + 'T00:00');
var year = selectedDate.getYear();
// Determine if it is a leap year (Feb has 29 days) and update array if so.
if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) {
daysInMonths[1] = 29;
}
var selectedDateMonth = selectedDate.getMonth();
// Get previous month number (if current month is January, get December)
let prevMonth = selectedDateMonth > 0 ? selectedDateMonth - 1 : 11;
let prevMonthDate = null;
// If selected date is last day of month...
if(selectedDate.getDate() === daysInMonths[selectedDateMonth]){
// Create new date that takes the selected date and subtracts the correct amount of
// days from it based on a lookup in the array.
var newDate1 = new Date(selectedDate.getTime());
prevMonthDate =
new Date(newDate1.setDate(selectedDate.getDate() - daysInMonths[selectedDateMonth]));
} else {
// Create a new date that is last month and one day earlier
var newDate2 = new Date(selectedDate.getTime());
prevMonthDate =
new Date(new Date(newDate2.setDate(selectedDate.getDate() - 1))
.setMonth(selectedDate.getMonth() - 1));
}
// Get next month (if current month is December, get January
let nextMonth = selectedDateMonth < 11 ? selectedDateMonth + 1 : 0;
let nextMonthDate = null;
// Same idea for next month, but add instead of subtract.
// If selected date is last day of month...
if(selectedDate.getDate() === daysInMonths[selectedDateMonth]){
var newDate3 = new Date(selectedDate.getTime());
nextMonthDate =
new Date(newDate3.setDate(selectedDate.getDate() + daysInMonths[selectedDateMonth + 1]));
} else {
var newDate4 = new Date(selectedDate.getTime());
nextMonthDate = new Date(new Date(newDate4.setDate(selectedDate.getDate() + 1)).setMonth(selectedDate.getMonth() + 1));
}
console.log("Last month date: " + prevMonthDate.toLocaleDateString());
console.log("Next month date: " + nextMonthDate.toLocaleDateString());
});
<p>Pick a date: <input type="date" id="date"></p>

Use this approach:
Javascript Date Object – Adding and Subtracting Months
From the Author
There is a slight problem with the Javascript Date() Object when trying to advance to the next month or go back to the previous month.
For example, if your date is set to October 31, 2018 and you add one month, you'd probably expect the new date to be November 30, 2018 because November 31st doesn't exist. This, however, isn't the case.
Javascript automatically advances your Date object to December 1st. This functionality is very useful in most situations(i.e. adding days to a date, determining the number of days in a month or if it's a leap year), but not for adding/subtracting months. I've put together some functions below that extend the Date() object: nextMonth() and prevMonth().
function prevMonth() {
var thisMonth = this.getMonth();
this.setMonth(thisMonth - 1);
if (this.getMonth() != thisMonth - 1 && (this.getMonth() != 11 || (thisMonth == 11 && this.getDate() == 1)))
this.setDate(0);
}
function nextMonth() {
var thisMonth = this.getMonth();
this.setMonth(thisMonth + 1);
if (this.getMonth() != thisMonth + 1 && this.getMonth() != 0)
this.setDate(0);
}
Date.prototype.nextMonth = nextMonth;
Date.prototype.prevMonth = prevMonth;
var today = new Date(2018, 2, 31); //<----- March 31st, 2018
var prevMonth = new Date(today.getTime());
prevMonth.prevMonth();
console.log("Previous month:", prevMonth);
console.log("This month:", today)
var nextMonth = new Date(today.getTime());
nextMonth.nextMonth();
console.log("Next month:", nextMonth);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Dates and time zones are a real pain in JS, so challenge accepted.
I broke it down in two steps:
- Count the days of prev and next month
- Compare with selected day and pick the lowest number
Testcases included
function createUTCDate(year, month, day) {
return new Date(Date.UTC(year, month, day));
}
function splitDate(date) {
return {
year: date.getUTCFullYear(),
month: date.getUTCMonth(),
day: date.getUTCDate()
};
}
function numberOfDaysInMonth(year, month) {
return new Date(year, month + 1, 0).getDate();
}
function dateNextMonth(dateObj) {
const daysNextMonth = numberOfDaysInMonth(dateObj.year, dateObj.month + 1);
const day = Math.min(daysNextMonth, dateObj.day);
return createUTCDate(dateObj.year, dateObj.month + 1, day);
}
function datePreviousMonth(dateObj) {
const daysPrevMonth = numberOfDaysInMonth(dateObj.year, dateObj.month - 1);
const day = Math.min(daysPrevMonth, dateObj.day);
return createUTCDate(dateObj.year, dateObj.month - 1, day);
}
const log = console.log;
function print(dateString) {
const date = new Date(dateString);
const dateObj = splitDate(date);
log("Previous: ", datePreviousMonth(dateObj).toISOString());
log("Selected: ", date.toISOString());
log("Next: ", dateNextMonth(dateObj).toISOString());
log("--------------");
}
const testCases = [
"2018-03-01 UTC",
"2018-03-31 UTC",
"2018-01-01 UTC",
"2018-12-31 UTC"
];
testCases.forEach(print);
Please note that the hack with new Date(xxx + " UTC") is not according to spec and is just there for testing purposes. Results may vary per browser.
You should choose an input format and construct your dates accordingly.

I handle it in a foolish way by concatenating string
let daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
var target = nexttarget = lasttarget = "29"; //target day
if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) {
daysInMonths[1] = 29;
}
function findLastDay(target, month){
if(target > daysInMonths[month]){
target = daysInMonths[month];
}
return target;
}
then
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
target = findLastDay(target, month);
var this_month = year+"-"+months[month]+"-"+target;
console.log(this_month);//2018-03-29
// next month
if(month == 11){
nextmonth = 0;
nextyear = year + 1;
}else{
nextmonth = month+1;
nextyear = year;
}
nexttarget = findLastDay(nexttarget, nextmonth);
var next_month = nextyear+"-"+months[nextmonth]+"-"+nexttarget;
console.log(next_month);//2018-04-29
//last month
if(month == 0){
lastmonth = 11;
lastyear = year - 1;
}else{
lastmonth = month - 1;
lastyear = year;
}
lasttarget = findLastDay(lasttarget, lastmonth);
var last_month = lastyear+"-"+months[lastmonth]+"-"+lasttarget;
console.log(last_month);//2018-02-28

Date handling is tricky at the best of times. Don't do this yourself. Use Moment.js.
var target = 31;
var today = moment().date(target).calendar();
// today == '03/31/2018'
var nextMonth = moment().date(target).add(1, 'month').calendar();
// nextMonth == '04/30/2018'
var lastMonth = moment().date(target).subtract(1, 'month').calendar()
// lastMonth == '02/28/2018'

Related

How to check if last day of month is on friday Javascript

I'm supposed to write a code for codewars to find out the number of times a month ends with a Friday within a range of years.
To start off, I did research and found out several solutions but I still couldn't figure out the results in the console.log.
The first solution is from this tutorial:
In this code, the solution is
let LastDay = new Date(1998, 5 + 1, 0).getDate();
I was able to get the date, but it wasn't clear which day the date falls upon.
Then I found another solution at w3schools. This solution also set the date to be the last day of this month:
var d = new Date();
d.setMonth(d.getMonth() +1, 0);
document.getElementById("demo").innerHTML = d;
However, it works if it displays it as innerHTML = Sat Nov 30 2019 00:57:09 GMT-0500 (Eastern Standard Time). However, when I tried to rewrite the code and console.log it like in this example:
let d = new Date();
let month = d.getMonth()+1;
let lastday = d.setMonth(month, 0);
console.log(lastday);
The result I got was 1575093343211. I don't understand how it displays those numbers instead of the dates I was expecting. I thought that if it does display the dates, starting with the day, I can convert the date to string or array and check if the first element is Friday and then add it to the counter in the code I'm writing. How do I get the code to display the way I want it to.
something like this will work...
function LastDayOfMonth(Year, Month) {
return new Date((new Date(Year, Month, 1)) - 1);
}
var d = LastDayOfMonth(new Date().getYear(), new Date().getMonth())
//var d = LastDayOfMonth(2009, 11)
var dayName = d.toString().split(' ')[0];
console.log(dayName)
The result I got was 1575093343211. I don't understand how it displays those numbers instead of the dates I was expecting
Because you console.log the output of the setMonth method, not the date object:
let lastday = d.setMonth(month, 0);
console.log(lastday);
According to the documentation, the setMonth method returns:
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Instead you should use that output to create a new instance of the date object:
let lastday = new Date(d.setMonth(month, 0));
console.log(lastday);
Algorithms to get the last day of the month are generally based on setting a date to day 0 of the following month, which ends up being the last day of the required month.
E.g. to get the last day for June, 2019 (noting that 6 is July, not June):
let endOfJune = new Date(2019, 6, 0):
Once you have the date, you can get the day where 0 is Sunday, 1 is Monday, etc. and 5 is Friday:
let endOfJuneDay = endOfJune.getDay();
The set* methods modify the Date they're called on and return the time value for the modified date. So you don't need to assign the result to anything:
let d = new Date();
let month = d.getMonth() + 1;
// Set date to the new month
d.setMonth(month, 0);
console.log(d);
So if you want to loop over the months for a range of years and get the number that end with a Friday (or any particular day), you might loop over the months something like:
/*
** #param {number} startYear - start year of range
** #param {number} endYear - end year of range
** #param {number} dat - day number, 0 = Sunday, 1 = Monday, etc.
** default is 0 (Sunday)
*/
function countEOMDay(startYear, endYear, day = 0) {
// startYear must be <= end year
if (startYear > endYear) return;
// Start on 31 Jan of start year
let start = new Date(startYear, 0, 31);
// End on 31 Dec of end year
let end = new Date(endYear, 11, 31);
let count = 0;
// Loop over months from start to end
while (start <= end) {
// Count matching days
if (start.getDay() == day) {
++count;
}
// Increment month to end of next month
start.setMonth(start.getMonth() + 2, 0);
}
return count;
}
console.log(countEOMDay(2019, 2019, 5)); // 1
console.log(countEOMDay(2018, 2019, 5)); // 3
You can use setMonth() method to set the month of a date object. The return value of setMonth() method is milliseconds between the date object and midnight January 1 1970. That's what you get from console.log(lastday);
Your return value,
1575093343211
is milliseconds between your date object (d) and midnight January 1 1970.
If you want to get the expected date, you have to console log your date object instead the lastday, as follows:
let d = new Date();
let month = d.getMonth()+1;
let lastday = d.setMonth(month, 0);
console.log(d);
output: Sat Nov 30 2019 00:02:47 GMT+0530 (India Standard Time)
This is an alternative solution I wrote to solve your problem. This will return the number of times a month ends with a Friday within a range of years. Hope this will help you :)
var days = [];
var count = 0;
function getLastFridaysCount(startYear, endYear) {
for (var year = startYear; year <= endYear; year++) {
days = [
31,
0 === year % 4 && 0 !== year % 100 || 0 === year % 400 ? 29 : 28,
31, 30, 31, 30, 31, 31, 30, 31, 30, 31
];
for (var month = 0; month <= 11; month++) {
var myDate = new Date();
myDate.setFullYear(year);
myDate.setMonth(month);
myDate.setDate(days[month]);
if(myDate.getDay() == 5)
{
count++;
}
}
}
return count;
}
console.log("count", getLastFridaysCount(2014, 2017));
this is the solution, in the code can find the comments "//" explaining of what happens in each iteration.
function lastDayIsFriday(initialYear, endYear) {
let count = 0;
//according to when the year ends starts the loop
if (endYear !== undefined) {
let start = new Date(initialYear, 0, 31);
let end = new Date(endYear, 11, 31);
while(start <= end) { //check if the start date is < or = to the end
//The getDay() method returns the day of the week (from 0 to 6) for the specified date.
if(start.getDay() === 5) { //if = to FriYAY!!!
count++; //count the day
}
start.setMonth(start.getMonth()+2, 0);// returns the month (from 0 to 11) .getMonth
} //& sets the month of a date object .setMonth
return count;
} else {
let start = new Date(initialYear, 0, 31);
console.log(start.toString());
for(let i = 0; i < 12; i++) {
if(start.getDay() === 5) {
count++;
}
start.setMonth(start.getMonth() + 2, 0);
// console.log(start.toString());
}
return count;
}
}

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());

Get next day, skip weekends

I want to generate next working day using JavaScript.
This is my code as of now
var today = new Date();
today.setDate(today.getDate());
var tdd = today.getDate();
var tmm = today.getMonth()+1;
var tyyyy = today.getYear();
var date = new Date();
date.setDate(date.getDate()+3);
Problem is, on Fridays it returns Saturday's date whereas I want it to be Monday
This will choose the next working day when a date is passed to it.
I suggest you normalise the date you pass, so you will not be surprised around summertime/wintertime change
Updated in 2023
const getNextWork = date => {
let day = date.getDay(), add = 1;
if (day === 6) add = 2; else
if (day === 5) add = 3;
date.setDate(date.getDate() + add); // will correctly handle 31+1 > 32 > 1st next month
return date;
};
// tests:
const dt = new Intl.DateTimeFormat("en-US", {
weekday: "short",
year: "numeric",
month: "long",
day: "numeric",
timeZone: "UTC",
timeZoneName: "short",
hour: "numeric",
minute: "numeric",
});
const aDay = 24 * 60 * 60 * 1000;
// 26th of March 2023 is daylight savings date in my country
let date = new Date(2023, 2, 24, 15, 0, 0, 0).getTime();
for (let i = 0; i < 7; i++) {
const d = new Date(date + i * aDay);
console.log(dt.format(d), "-->", dt.format(getNextWork(d)));
}
Older code:
var today = new Date(2016, 7, 26,12,0,0,0,0); // Friday at noon
console.log("today, Monday",today,"day #"+today.getDay());
var next = new Date(today.getTime());
next.setDate(next.getDate()+1); // tomorrow
while (next.getDay() == 6 || next.getDay() == 0) next.setDate(next.getDate() + 1);
console.log("no change ",next,"day #"+next.getDay());
console.log("-------");
// or without a loop:
function getNextWork(d) {
d.setDate(d.getDate()+1); // tomorrow
if (d.getDay()==0) d.setDate(d.getDate()+1);
else if (d.getDay()==6) d.setDate(d.getDate()+2);
return d;
}
next = getNextWork(today); // Friday
console.log("today, Friday",today);
console.log("next, Monday ",next);
console.log("-------");
today = new Date(2016, 7, 29,12,0,0,0); // Monday at noon
next = getNextWork(today); // Still Monday at noon
console.log("today, Monday",today);
console.log("no change ",next);
console.log("-------");
// Implementing Rob's comment
function getNextWork1(d) {
var day = d.getDay(),add=1;
if (day===5) add=3;
else if (day===6) add=2;
d.setDate(d.getDate()+add);
return d;
}
today = new Date(2016, 7, 26,12,0,0,0,0); // Friday at noon
next = getNextWork1(today); // Friday
console.log("today, Friday",today);
console.log("next, Monday ",next);
console.log("-------");
today = new Date(2016, 7, 26,12,0,0,0,0); // Monday at noon
next = getNextWork1(today); // Monday
console.log("today, Monday",today);
console.log("no change ",next);
You can add 1 day at at time until you get to a day that isn't Saturday or Sunday:
function getNextBusinessDay(date) {
// Copy date so don't affect original
date = new Date(+date);
// Add days until get not Sat or Sun
do {
date.setDate(date.getDate() + 1);
} while (!(date.getDay() % 6))
return date;
}
// today, Friday 26 Aug 2016
[new Date(), new Date(2016,7,26)].forEach(function(d) {
console.log(d.toLocaleString() + ' : ' + getNextBusinessDay(d).toLocaleString());
});
You can also test the day and add extra to get over the weekend:
// Classic Mon to Fri
function getNextWorkDay(date) {
let d = new Date(+date);
let day = d.getDay() || 7;
d.setDate(d.getDate() + (day > 4? 8 - day : 1));
return d;
}
for (let i=0, d=new Date(); i<7; i++) {
console.log(`${d.toDateString()} -> ${getNextWorkDay(d).toDateString()}`);
d.setDate(d.getDate() + 1);
}
Here is another approach where the work week can be specified using ECMAScript weekday numbers (Sun = 0, Mon = 1, etc.). Dates outside the range are shifted to the start of the next work week.
This is useful where the week is not the classic Mon to Fri, such as the Middle East where Sat to Wed is common or for some who might work Fri to Mon (or whatever).
function getNext(start, end, date) {
let d = new Date(+date);
d.setDate(d.getDate() + 1);
let day = d.getDay();
// Adjust end and day if necessary
// The order of tests and adjustment is important
if (end < start) {
if (day <= end) {
day += 7;
}
end += 7;
}
// If day is before start, shift to start
if (day < start) {
d.setDate(d.getDate() + start - day);
// If day is after end, shift to next start (treat Sunday as 7)
} else if (day > end) {
d.setDate(d.getDate() + 8 - (day || 7));
}
return d;
}
// Examples
let f = new Intl.DateTimeFormat('en-GB', {
weekday:'short',day:'2-digit', month:'short'});
let d = new Date();
[{c:'Work days Mon to Fri',s:1,e:5},
{c:'Work days Sat to Wed',s:6,e:3},
{c:'Work days Fri to Mon',s:5,e:1}
].forEach(({c,s,e}) => {
for (let i = 0; i < 7; i++) {
!i? console.log(`\n${c}`) : null;
console.log(`${f.format(d)} => ${f.format(getNext(s, e, d))}`);
d.setDate(d.getDate() + 1);
}
});
Check this out: https://jsfiddle.net/e9a4066r/
function get_next_weekday (date) {
var tomorrow = new Date(date.setDate(date.getDate() + 1))
return tomorrow.getDay() % 6
? tomorrow
: get_next_weekday(tomorrow)
}
The accepted answer will skip one day at a time, which answers the OPs question, but for anyone looking to add a variable number of days while still skipping weekends the function below may be helpful:
function addWorkDays(date, days) {
while (days > 0) {
date.setDate(date.getDate() + 1);
if (date.getDay() != 0 && date.getDay() != 6) {
days -= 1;
}
}
return date;
}
Thought I'd throw my hat in the ring here with:
function getNextBusinessDate(date) {
// Create date array [S, M, T, W, T, F, S]
const days = new Array(7);
let nextDate = date;
for(let i = 0; i < 7; i++) {
days[nextDate.getDay()] = new Date(nextDate);
nextDate.setDate(nextDate.getDate() + 1);
}
// Shift indices to index as though array was [M, T, W, T, F, S, S]
// Then truncate with min to make F, S, S all yield M for next date
return days[Math.min((date.getDay() + 6) % 7 + 1, 5) % 5 + 1];
}

How can I get the 4 Mondays of a month with js?

I'm building a chart where the x-axis should be the four weeks of a month. I would like to display only the four Mondays of that month.
I already have the currentMonth and the currentYear variables, and I know how to get the first day of the month. All I need is to get the four Mondays of a month in an array. And all of this in the same JavaScript file.
I'm pretty lost within my programming logic, and I've seen plenty of solutions that don't fit my use case.
Right now, I have:
var date = new Date();
var currentYear = date.getFullYear();
var currentMonth = date.getMonth();
var firstDayofMonth = new Date(currentYear, currentMonth, 1);
var firstWeekDay = firstDayofMonth.getDay();
but I would like to have something like this:
var myDates = [
new Date(firstMonday),
new Date(secondMonday),
new Date(thirdMonday),
new Date(fourthMonday),
];
The following function will return all Mondays for the current month:
function getMondays() {
var d = new Date(),
month = d.getMonth(),
mondays = [];
d.setDate(1);
// Get the first Monday in the month
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getMonth() === month) {
mondays.push(new Date(d.getTime()));
d.setDate(d.getDate() + 7);
}
return mondays;
}
This would return the fourth last monday of month [m] in year [y]
function lastmonday(y,m) {
var dat = new Date(y+'/'+m+'/1')
,currentmonth = m
,firstmonday = false;
while (currentmonth === m){
firstmonday = dat.getDay() === 1 || firstmonday;
dat.setDate(dat.getDate()+(firstmonday ? 7 : 1));
currentmonth = dat.getMonth()+1;
}
dat.setDate(dat.getDate()-7);
return dat;
}
// usage
lastmonday(2012,3); //=>Mon Mar 26 2012 00:00:00 GMT+0200
lastmonday(2012,2) //=>Mon Feb 27 2012 00:00:00 GMT+0100
lastmonday(1997,1) //=>Mon Jan 27 1997 00:00:00 GMT+0100
lastmonday(2012,4) //=>Mon Apr 30 2012 00:00:00 GMT+0200
To be more generic, this will deliver the last any weekday of a month:
function lastDayOfMonth(y,m,dy) {
var days = {sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}
,dat = new Date(y+'/'+m+'/1')
,currentmonth = m
,firstday = false;
while (currentmonth === m){
firstday = dat.getDay() === days[dy] || firstday;
dat.setDate(dat.getDate()+(firstday ? 7 : 1));
currentmonth = dat.getMonth()+1 ;
}
dat.setDate(dat.getDate()-7);
return dat;
}
// usage
lastDayOfMonth(2012,2,'tue'); //=>Tue Feb 28 2012 00:00:00 GMT+0100
lastDayOfMonth(1943,5,'fri'); //=>Fri May 28 1943 00:00:00 GMT+0200
For whoever may need, this is a general function to get every monday, tuesday, etc
getDatesOfDayOfWeek (year, month, dayOfWeek) {
const initialDate = new Date(year, month, 1);
const datesOfDayOfWeek = [];
while (initialDate.getDay() !== dayOfWeek) {
initialDate.setDate(initialDate.getDate() + 1);
}
while (initialDate.getMonth() === month) {
const nextDate = new Date(initialDate.getTime());
datesOfDayOfWeek.push(nextDate.getDate());
initialDate.setDate(initialDate.getDate() + 7);
}
return datesOfDayOfWeek;
}
I took Jake's code and generalized it to get the next N occurrences of a particular schedule. (e.g. "Get me the next 10 instances of 2nd Mondays and 1st and 3rd Wednesdays.")
schedule is an object with keys for day-of-week whose values are
an array of the incident within a month that the DoW falls.
keys can include numbers from 1-5, and -1 for "last."
items in a value array can include numbers from 0-6, where 0 is Sunday.
count is optional (defaults to 6) and represents how many items to show.
Samples
First and third Mondays would be nextNthMdays({1: [1, 3]})
Second Wed and Fri would be nextNthMdays({3: [2], 5: [2]})
Last Thursdays would be nextNthMdays({4: [-1]})
function nextNthMdays(schedule, count) {
var d = new Date(),
month = 999,
nthInMonth,
dates = [];
if (count == undefined) {
count = 6;
}
// start at the beginning of the month
d.setDate(1);
// Iterate until we have enough
while (dates.length < count) {
var day = d.getDay();
// Reset counters each month
if (d.getMonth() !== month) {
month = d.getMonth();
nthInMonth = Object.keys(schedule).reduce(function (obj, x) {
obj[x] = 0;
return obj;
}, {});
}
// When you reach an interesting weekday
if (day in schedule) {
// Increment its counter
nthInMonth[day]++;
// If it's after today
if (d > new Date()) {
// and its counter matches
if (schedule[day].indexOf(nthInMonth[day]) !== -1) {
// Add it
dates.push(new Date(d.getTime()));
}
// or if we want the last one
else if (schedule[day].indexOf(-1) !== -1) {
// verify that 7 days from then is a different month
var sevenAway = new Date(d);
sevenAway.setDate(sevenAway.getDate() + 7);
if (d.getMonth() !== sevenAway.getMonth()) {
// Add it
dates.push(new Date(d.getTime()));
}
}
}
}
// Move on to the next day
d.setDate(d.getDate() + 1);
}
return dates;
}
Demonstration
Expand the snippet to run some examples.
// `schedule` is an object with keys
// for day-of-week whose values are
// an array of the incident within
// a month that the DoW falls.
//
// keys can include numbers from
// 1-5, and -1 for "last."
// items in a value array can include
// numbers from 0-6, where 0 is
// Sunday.
//
// `count` is optional (defaults to 6)
// and represents how many items to
// show.
//
// First and third Mondays would be
// nextNthMdays({1: [1, 3]})
// Second Wed and Fri would be
// nextNthMdays({3: [2], 5: [2]})
// Last Thursdays would be
// nextNthMdays(4: [-1])
function nextNthMdays(schedule, count) {
var d = new Date(),
month = 999,
nthInMonth,
dates = [];
if (count == undefined) {
count = 6;
}
// start at the beginning of the month
d.setDate(1);
// Iterate until we have enough
while (dates.length < count) {
var day = d.getDay();
// Reset counters each month
if (d.getMonth() !== month) {
month = d.getMonth();
nthInMonth = Object.keys(schedule).reduce(function (obj, x) {
obj[x] = 0;
return obj;
}, {});
}
// When you reach an interesting weekday
if (day in schedule) {
// Increment its counter
nthInMonth[day]++;
// If it's after today
if (d > new Date()) {
// and its counter matches
if (schedule[day].indexOf(nthInMonth[day]) !== -1) {
// Add it
dates.push(new Date(d.getTime()));
}
// or if we want the last one
else if (schedule[day].indexOf(-1) !== -1) {
// verify that 7 days from then is a different month
var sevenAway = new Date(d);
sevenAway.setDate(sevenAway.getDate() + 7);
if (d.getMonth() !== sevenAway.getMonth()) {
// Add it
dates.push(new Date(d.getTime()));
}
}
}
}
// Move on to the next day
d.setDate(d.getDate() + 1);
}
return dates;
}
console.log('Next third Wednesdays');
console.log(nextNthMdays({3: [3],}));
console.log('Next first and third Mondays');
console.log(nextNthMdays({1: [1, 3],}, 4));
console.log('Next second Wed/Fridays');
console.log(nextNthMdays({3: [2], 5: [2],}, 3));
console.log('Next "Last Thursdays of the month"');
console.log(nextNthMdays({4: [-1],}, 3));

How to convert a week number to a date in Javascript

I had tried to find some work done but I haven't had luck. Any ideas?
Examples:
Week, 1, 2001 => 2001-01-01
Week, 26, 2007 => 2007-06-01
As Kevin's code does not implement ISO 8601 properly (first day of the first week of year must be a Monday), I've corrected it and ended up with (also check it on jsfiddle):
function firstDayOfWeek(week, year) {
if (year==null) {
year = (new Date()).getFullYear();
}
var date = firstWeekOfYear(year),
weekTime = weeksToMilliseconds(week),
targetTime = date.getTime() + weekTime;
return date.setTime(targetTime);
}
function weeksToMilliseconds(weeks) {
return 1000 * 60 * 60 * 24 * 7 * (weeks - 1);
}
function firstWeekOfYear(year) {
var date = new Date();
date = firstDayOfYear(date,year);
date = firstWeekday(date);
return date;
}
function firstDayOfYear(date, year) {
date.setYear(year);
date.setDate(1);
date.setMonth(0);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
/**
* Sets the given date as the first day of week of the first week of year.
*/
function firstWeekday(firstOfJanuaryDate) {
// 0 correspond au dimanche et 6 correspond au samedi.
var FIRST_DAY_OF_WEEK = 1; // Monday, according to iso8601
var WEEK_LENGTH = 7; // 7 days per week
var day = firstOfJanuaryDate.getDay();
day = (day === 0) ? 7 : day; // make the days monday-sunday equals to 1-7 instead of 0-6
var dayOffset=-day+FIRST_DAY_OF_WEEK; // dayOffset will correct the date in order to get a Monday
if (WEEK_LENGTH-day+1<4) {
// the current week has not the minimum 4 days required by iso 8601 => add one week
dayOffset += WEEK_LENGTH;
}
return new Date(firstOfJanuaryDate.getTime()+dayOffset*24*60*60*1000);
}
function assertDateEquals(effectiveDate, expectedDate, description) {
if ((effectiveDate==null ^ expectedDate==null) || effectiveDate.getTime()!=expectedDate.getTime()) {
console.log("assert failed: "+description+"; effective="+effectiveDate+", expected="+expectedDate);
}
}
function assertEquals(effectiveValue, expectedValue, description) {
if (effectiveValue!=expectedValue) {
console.log("assert failed: "+description+"; effective="+effectiveValue+", expected="+expectedValue);
}
}
// expect the first day of year to be a monday
for (var i=1970; i<2050; i++) {
assertEquals(firstWeekOfYear(i).getDay(), 1, "first day of year "+i+" must be a monday"); // 1=Monday
}
// assert some future first day of first week of year; source: http://www.epochconverter.com/date-and-time/weeknumbers-by-year.php
assertDateEquals(firstWeekOfYear(2013), new Date(Date.parse("Dec 31, 2012")), "2013");
assertDateEquals(firstWeekOfYear(2014), new Date(Date.parse("Dec 30, 2013")), "2014");
assertDateEquals(firstWeekOfYear(2015), new Date(Date.parse("Dec 29, 2014")), "2015");
assertDateEquals(firstWeekOfYear(2016), new Date(Date.parse("Jan 4, 2016")), "2016");
assertDateEquals(firstWeekOfYear(2017), new Date(Date.parse("Jan 2, 2017")), "2017");
assertDateEquals(firstWeekOfYear(2018), new Date(Date.parse("Jan 1, 2018")), "2018");
assertDateEquals(firstWeekOfYear(2019), new Date(Date.parse("Dec 31, 2018")), "2019");
assertDateEquals(firstWeekOfYear(2020), new Date(Date.parse("Dec 30, 2019")), "2020");
assertDateEquals(firstWeekOfYear(2021), new Date(Date.parse("Jan 4, 2021")), "2021");
assertDateEquals(firstWeekOfYear(2022), new Date(Date.parse("Jan 3, 2022")), "2022");
assertDateEquals(firstWeekOfYear(2023), new Date(Date.parse("Jan 2, 2023")), "2023");
assertDateEquals(firstWeekOfYear(2024), new Date(Date.parse("Jan 1, 2024")), "2024");
assertDateEquals(firstWeekOfYear(2025), new Date(Date.parse("Dec 30, 2024")), "2025");
assertDateEquals(firstWeekOfYear(2026), new Date(Date.parse("Dec 29, 2025")), "2026");
console.log("All assertions done.");
I included test cases for some dates to check that the first day of the first week of year is a Monday and checked some dates based on http://www.epochconverter.com/date-and-time/weeknumbers-by-year.php
Someone might be still interested in a more contained version:
function firstDayOfWeek (year, week) {
// Jan 1 of 'year'
var d = new Date(year, 0, 1),
offset = d.getTimezoneOffset();
// ISO: week 1 is the one with the year's first Thursday
// so nearest Thursday: current date + 4 - current day number
// Sunday is converted from 0 to 7
d.setDate(d.getDate() + 4 - (d.getDay() || 7));
// 7 days * (week - overlapping first week)
d.setTime(d.getTime() + 7 * 24 * 60 * 60 * 1000
* (week + (year == d.getFullYear() ? -1 : 0 )));
// daylight savings fix
d.setTime(d.getTime()
+ (d.getTimezoneOffset() - offset) * 60 * 1000);
// back to Monday (from Thursday)
d.setDate(d.getDate() - 3);
return d;
}
I took the original idea from Kevin, with some tweaks, coz the original code is returning milliseconds. Here you go:
var d = firstDayOfWeek(9, 2013);
console.log(d.format("yyyy-MM-dd"));
////////////////////////////// Main Code //////////////////////////////
function firstDayOfWeek(week, year) {
if (typeof year !== 'undefined') {
year = (new Date()).getFullYear();
}
var date = firstWeekOfYear(year),
weekTime = weeksToMilliseconds(week),
targetTime = date.getTime() + weekTime - 86400000;
var result = new Date(targetTime)
return result;
}
function weeksToMilliseconds(weeks) {
return 1000 * 60 * 60 * 24 * 7 * (weeks - 1);
}
function firstWeekOfYear(year) {
var date = new Date();
date = firstDayOfYear(date,year);
date = firstWeekday(date);
return date;
}
function firstDayOfYear(date, year) {
date.setYear(year);
date.setDate(1);
date.setMonth(0);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
function firstWeekday(date) {
var day = date.getDay(),
day = (day === 0) ? 7 : day;
if (day > 3) {
var remaining = 8 - day,
target = remaining + 1;
date.setDate(target);
}
return date;
}
Take a look at this fiddle. First, it gets the first week of the specified year. This takes into account that according to ISO 8601 the first week of the year is the first week containing a wednesday. Then it adds the weeks to the acquired date and returns the result.
function firstDayOfWeek(week, year) {
var date = firstWeekOfYear(year),
weekTime = weeksToMilliseconds(week),
targetTime = weekTime + date.getTime();
return date.setTime(targetTime);
}

Categories