HOW to display javascript output in a html textbox - javascript

i have a script that helps to calculate working days between two days with JavaScript but i want to send the output to a MySQL database.
Like the value at the end of the code "dif" that outputs in the span to be writing to a mysql database or if i can place it in a text box and eventually post it to database
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head><body>
<script>
$(document).ready(() => {
$('#calc').click(() => {
var d1 = $('#d1').val();
var d2 = $('#d2').val();
$('#dif').text(workingDaysBetweenDates(d1,d2));
});
});
let workingDaysBetweenDates = (d0, d1) => {
/* Two working days and an sunday (not working day) */
var holidays = ['2020/04/06', '2020/06/04', '06/04/2020','04/06/2020'];
var startDate = parseDate(d0);
var endDate = parseDate(d1);
// Validate input
if (endDate < startDate) {
return 0;
}
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days -= weeks * 2;
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1) {
days -= 2;
}
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6) {
days--;
}
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0) {
days--;
}
/* Here is the code */
holidays.forEach(day => {
if ((day >= d0) && (day <= d1)) {
/* If it is not saturday (6) or sunday (0), substract it */
if ((parseDate(day).getDay() % 6) != 0) {
days--;
}
}
});
return days;
}
function parseDate(input) {
// Transform date from text to date
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
</script>
<input type="date" id="d1" value="06/06/2020"><br>
<input type="date" id="d2" value="05/06/2020">
<p>Working days count: <span id="dif"></span></p>
<button id="calc">Calc</button>
</body>
</html>
database please help here is the script.

To send any data to a database, you'll need to utilize a POST request to your server. To do this, you'll want to wrap whatever it is you plan on sending to the database (in your case, the dif) in an HTML form element. Inside the form element, store that dif variable as a value of an input element (you can hide this element if you wish), then use an AJAX call or a HTTP Request to send that data to the server.
For more information on how to apply this to your situation, check out this quick little rundown

Related

Show next date while skipping holidays in javascript [duplicate]

I have a javascript function which is calculating working days between 2 dates, it works, but the problem is that it not consider holidays. How can I modify this function, for example by adding holidays in exception array?
Searched in internet about this question, but haven't find about holidays exception.
For example holidays array:
var holidays = ['2016-05-03','2016-05-05'];
And I have a functions to calculate this:
function workingDaysBetweenDates(d0, d1) {
var startDate = parseDate(d0);
var endDate = parseDate(d1);
// Validate input
if (endDate < startDate)
return 0;
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0,0,0,1); // Start just after midnight
endDate.setHours(23,59,59,999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days = days - (weeks * 2);
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1)
days = days - 2;
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6)
days = days - 1
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0)
days = days - 1
return days;
}
function parseDate(input) {
// Transform date from text to date
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
Have made an example in jsfiddle:
JSFiddle example
Maybe there are some other functions which can easy use in Jquery?
Try:
var startDate = new Date('05/03/2016');
var endDate = new Date('05/10/2016');
var numOfDates = getBusinessDatesCount(startDate,endDate);
function getBusinessDatesCount(startDate, endDate) {
let count = 0;
const curDate = new Date(startDate.getTime());
while (curDate <= endDate) {
const dayOfWeek = curDate.getDay();
if(dayOfWeek !== 0 && dayOfWeek !== 6) count++;
curDate.setDate(curDate.getDate() + 1);
}
alert(count);
return count;
}
The easiest way to achieve it is looking for these days between your begin and end date.
Edit: I added an additional verification to make sure that only working days from holidays array are subtracted.
$(document).ready(() => {
$('#calc').click(() => {
var d1 = $('#d1').val();
var d2 = $('#d2').val();
$('#dif').text(workingDaysBetweenDates(d1,d2));
});
});
let workingDaysBetweenDates = (d0, d1) => {
/* Two working days and an sunday (not working day) */
var holidays = ['2016-05-03', '2016-05-05', '2016-05-07'];
var startDate = parseDate(d0);
var endDate = parseDate(d1);
// Validate input
if (endDate <= startDate) {
return 0;
}
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days -= weeks * 2;
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1) {
days -= 2;
}
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6) {
days--;
}
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0) {
days--;
}
/* Here is the code */
holidays.forEach(day => {
if ((day >= d0) && (day <= d1)) {
/* If it is not saturday (6) or sunday (0), substract it */
if ((parseDate(day).getDay() % 6) != 0) {
days--;
}
}
});
return days;
}
function parseDate(input) {
// Transform date from text to date
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="d1" value="2016-05-02"><br>
<input type="text" id="d2" value="2016-05-08">
<p>Working days count: <span id="dif"></span></p>
<button id="calc">Calc</button>
<p>
Now it shows 5 days, but I need for example add holidays
3 and 5 May (2016-05-03 and 2016-05-05) so the result will be 3 working days
</p>
I took a similar approach to #OscarGarcia mainly as an excercise since my JS is rusty.
While it looks similar, it takes care not to substract a day twice if a holiday happens to be on a saturday or sunday. This way, you can pre-load a list of recurring dates (such as Dec 25th, Jan 1st, July 4th, which may or may not be on an otherwise working day -monday thru friday-)
$(document).ready(function(){
$('#calc').click(function(){
var d1 = $('#d1').val();
var d2 = $('#d2').val();
$('#dif').text(workingDaysBetweenDates(d1,d2));
});
});
function workingDaysBetweenDates(d0, d1) {
var startDate = parseDate(d0);
var endDate = parseDate(d1);
// populate the holidays array with all required dates without first taking care of what day of the week they happen
var holidays = ['2018-12-09', '2018-12-10', '2018-12-24', '2018-12-31'];
// Validate input
if (endDate < startDate)
return 0;
var z = 0; // number of days to substract at the very end
for (i = 0; i < holidays.length; i++)
{
var cand = parseDate(holidays[i]);
var candDay = cand.getDay();
if (cand >= startDate && cand <= endDate && candDay != 0 && candDay != 6)
{
// we'll only substract the date if it is between the start or end dates AND it isn't already a saturday or sunday
z++;
}
}
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0,0,0,1); // Start just after midnight
endDate.setHours(23,59,59,999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days = days - (weeks * 2);
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1)
days = days - 2;
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6)
days = days - 1
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0)
days = days - 1
// substract the holiday dates from the original calculation and return to the DOM
return days - z;
}
function parseDate(input) {
// Transform date from text to date
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
2018-12-09 is a sunday... with this code, it'll only be substracted once (for being a sunday) and not twice (as it would if we only checked if its a national holiday)
I think this solution is much more simpler
const numberOfDaysInclusive = (d0, d1) => {
return 1 + Math.round((d1.getTime()-d0.getTime())/(24*3600*1000));
}
const numberOfWeekends = (d0, d1) => {
const days = numberOfDaysInclusive(d0, d1); // total number of days
const sundays = Math.floor((days + (d0.getDay() + 6) % 7) / 7); // number of sundays
return 2*sundays + (d1.getDay()==6) - (d0.getDay()==0); // multiply sundays by 2 to get both sat and sun, +1 if d1 is saturday, -1 if d0 is sunday
}
const numberOfWeekdays = (d0, d1) => {
return numberOfDaysInclusive(d0, d1) - numberOfWeekends(d0, d1);
}
Get all weekdays between two dates:
private getCorrectWeekDays(StartDate,EndDate){
let _weekdays = [0,1,2,3,4];
var wdArr= [];
var currentDate = StartDate;
while (currentDate <= EndDate) {
if ( _weekdays.includes(currentDate.getDay())){
wdArr.push(currentDate);
//if you want to format it to yyyy-mm-dd
//wdArr.push(currentDate.toISOString().split('T')[0]);
}
currentDate.setDate(currentDate.getDate() +1);
}
return wdArr;
}
You can also try this piece of code:
const moment = require('moment-business-days');
/**
*
* #param {String} date - iso Date
* #returns {Number} difference between now and #param date
*/
const calculateDaysLeft = date => {
try {
return moment(date).businessDiff(moment(new Date()))
} catch (err) {
throw new Error(err)
}
}
The top answer actually works but with a flaw.
When the holyday is in a Saturday or Sunday it still reduces a day.
Add this to the existing code:
.... /* Here is the code */
for (var i in holidays) {
if ((holidays[i] >= d0) && (holidays[i] <= d1)) {
// Check if specific holyday is Saturday or Sunday
var yourDate = new Date(holidays[i]);
if(yourDate.getDay() === 6 || yourDate.getDay() === 0){
// If it is.. do nothing
} else {
// if it is not, reduce a day..
days--;
}
}
}
const workday_count = (start, end) => {
start = moment(start).format(("YYYY-MM-DD"))
end = moment(end).format(("YYYY-MM-DD"))
let workday_count = 0;
let totalDays = moment(end).diff(moment(start), "days");
let date = start
for (let i = 1; i <= totalDays; i++) {
if (i == 1) {
date = moment(date)
} else {
date = moment(date).add(1, "d");
}
date = new Date(date);
let dayOfWeek = date.getDay();
let isWeekend = (dayOfWeek === 6) || (dayOfWeek === 0);
if (!isWeekend) {
workday_count = workday_count + 1;
}
}
return workday_count;
}
Simply reduce the length of array from the value you have got (in your fiddle)
var numberofdayswithoutHolidays= 5;
var holidays = ['2016-05-03','2016-05-05'];
alert( numberofdayswithoutHolidays - holidays.length );
You need to filter out weekends from holidays as well
holidays = holidays.filter( function(day){
var day = parseDate( day ).getDay();
return day > 0 && day < 6;
})
$(document).ready(() => {
$('#calc').click(() => {
var d1 = $('#d1').val();
var d2 = $('#d2').val();
$('#dif').text(workingDaysBetweenDates(d1,d2));
});
});
let workingDaysBetweenDates = (d0, d1) => {
/* Two working days and an sunday (not working day) */
var holidays = ['2016-05-03', '2016-05-05', '2016-05-07'];
var startDate = parseDate(d0);
var endDate = parseDate(d1);
// Validate input
if (endDate < startDate) {
return 0;
}
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days -= weeks * 2;
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1) {
days -= 2;
}
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6) {
days--;
}
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0) {
days--;
}
/* Here is the code */
holidays.forEach(day => {
if ((day >= d0) && (day <= d1)) {
/* If it is not saturday (6) or sunday (0), substract it */
if ((parseDate(day).getDay() % 6) != 0) {
days--;
}
}
});
return days;
}
function parseDate(input) {
// Transform date from text to date
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="d1" value="2016-05-02"><br>
<input type="text" id="d2" value="2016-05-08">
<p>Working days count: <span id="dif"></span></p>
<button id="calc">Calc</button>
<p>
Now it shows 5 days, but I need for example add holidays
3 and 5 May (2016-05-03 and 2016-05-05) so the result will be 3 working days
</p>

How to check if date is in this week in javascript?

I have this date "2016-04-23T11:45:00Z" and I want to check this date in this week or not ?
Thanks,
Dates are hard, I would always suggest using a library dedicated to date handling as it reduces the chances of errors in your code.
MomentJS is a good one.
var now = moment();
var input = moment("2016-04-17T11:45:00Z");
var isThisWeek = (now.isoWeek() == input.isoWeek())
Edit: Please note as of 2020 moment may not be a good choice for new projects
This seems to be working for me.
function isDateInThisWeek(date) {
const todayObj = new Date();
const todayDate = todayObj.getDate();
const todayDay = todayObj.getDay();
// get first date of week
const firstDayOfWeek = new Date(todayObj.setDate(todayDate - todayDay));
// get last date of week
const lastDayOfWeek = new Date(firstDayOfWeek);
lastDayOfWeek.setDate(lastDayOfWeek.getDate() + 6);
// if date is equal or within the first and last dates of the week
return date >= firstDayOfWeek && date <= lastDayOfWeek;
}
const date = new Date();
const isInWeek = isDateInThisWeek(date);
<div ng-app="myApp">
<div class="container" ng-controller="Ctrl_List">
<h1>{{currentDate}}</h1>
<h1>{{numberCurrentDateWeeks}}</h1>
<h1>{{yourDate}}</h1>
<h1>{{numberYourDateWeeks}}</h1>
</div>
</div>
......
angular.module('myApp', [])
.controller("Ctrl_List", ["$scope", "$filter", function(s, $filter) {
s.yourDate = '2016-04-23T11:45:00Z'
s.currentDate = new Date();
s.numberCurrentDateWeeks = $filter('date')(s.currentDate, "w");
s.numberYourDateWeeks = $filter('date')(s.yourDate, "w");
}]);
then you got the Week numbers just compare or do whatever you like
cheers !
You can do that without any libraries by checking if the date.getTime() (milliseconds since epoch) is between last monday and next monday:
const WEEK_LENGTH = 604800000;
function onCurrentWeek(date) {
var lastMonday = new Date(); // Creating new date object for today
lastMonday.setDate(lastMonday.getDate() - (lastMonday.getDay()-1)); // Setting date to last monday
lastMonday.setHours(0,0,0,0); // Setting Hour to 00:00:00:00
const res = lastMonday.getTime() <= date.getTime() &&
date.getTime() < ( lastMonday.getTime() + WEEK_LENGTH);
return res; // true / false
}
(one week in ms = 24 * 60 * 60 * 1000 * 7 = 604,800,000)
May not be the most optimal solution, but I think it's quite readable:
function isThisWeek (date) {
const now = new Date();
const weekDay = (now.getDay() + 6) % 7; // Make sure Sunday is 6, not 0
const monthDay = now.getDate();
const mondayThisWeek = monthDay - weekDay;
const startOfThisWeek = new Date(+now);
startOfThisWeek.setDate(mondayThisWeek);
startOfThisWeek.setHours(0, 0, 0, 0);
const startOfNextWeek = new Date(+startOfThisWeek);
startOfNextWeek.setDate(mondayThisWeek + 7);
return date >= startOfThisWeek && date < startOfNextWeek;
}
This link explaines, how to do this without using any js libraries. https://gist.github.com/dblock/1081513
Code against link death:
function( d ) {
// Create a copy of this date object
var target = new Date(d.valueOf());
// ISO week date weeks start on monday
// so correct the day number
var dayNr = (d.getDay() + 6) % 7;
// Set the target to the thursday of this week so the
// target date is in the right year
target.setDate(target.getDate() - dayNr + 3);
// ISO 8601 states that week 1 is the week
// with january 4th in it
var jan4 = new Date(target.getFullYear(), 0, 4);
// Number of days between target date and january 4th
var dayDiff = (target - jan4) / 86400000;
// Calculate week number: Week 1 (january 4th) plus the
// number of weeks between target date and january 4th
var weekNr = 1 + Math.ceil(dayDiff / 7);
return weekNr;
}
I managed to do it with this simple trick and without any external library.
Considering monday as the first day of the week, the function takes as parameter a date string and do the validation before checking if the day indeed is in the current week.
function isInThisWeek(livr){
const WEEK = new Date()
// convert delivery date to Date instance
const DATEREF = new Date(livr)
// Check if date instance is in valid format (depends on the function arg)
if(DATEREF instanceof Date && isNaN(DATEREF)){
console.log("invalid date format")
return false}
// Deconstruct to get separated date infos
const [dayR, monthR, yearR] = [DATEREF.getDate(), DATEREF.getMonth(), DATEREF.getFullYear()]
// get Monday date
const monday = (WEEK.getDate() - WEEK.getDay()) + 1
// get Saturday date
const sunday = monday + 6
// Start verification
if (yearR !== WEEK.getFullYear()) { console.log("WRONG YEAR"); return false }
if (monthR !== WEEK.getMonth()) { console.log("WRONG MONTH"); return false }
if(dayR >= monday && dayR <= sunday) { return true }
else {console.log("WRONG DAY"); return false}
}
In the comments I saw that you stated that your week starts on Monday.
In that case, I guess it'd be a good idea to calculate the ISO week number of the 2 dates and see if you get the same week number for both of them.
To calculate the ISO week number, check this answer:
In case anyone else's week starts on Sunday instead, you can use this answer to calculate the week number accordingly.
then you can do something like this:
function isSameWeek(date1, date2) {
return date1.getWeekNumber() === date2.getWeekNumber();
}
const isDateInThisWeek = (date) => {
const today = new Date();
//Get the first day of the current week (Sunday)
const firstDayOfWeek = new Date(
today.setDate(today.getDate() - today.getDay())
);
//Get the last day of the current week (Saturday)
const lastDayOfWeek = new Date(
today.setDate(today.getDate() - today.getDay() + 6)
);
//check if my value is between a minimum date and a maximum date
if (date >= firstDayOfWeek && date <= lastDayOfWeek) {
return true;
} else {
return false;
}
};

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

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

JavaScript - get the first day of the week from current date

I need the fastest way to get the first day of the week. For example: today is the 11th of November, and a Thursday; and I want the first day of this week, which is the 8th of November, and a Monday. I need the fastest method for MongoDB map function, any ideas?
Using the getDay method of Date objects, you can know the number of day of the week (being 0=Sunday, 1=Monday, etc).
You can then subtract that number of days plus one, for example:
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));
}
getMonday(new Date()); // Mon Nov 08 2010
Not sure how it compares for performance, but this works.
var today = new Date();
var day = today.getDay() || 7; // Get current day number, converting Sun. to 7
if( day !== 1 ) // Only manipulate the date if it isn't Mon.
today.setHours(-24 * (day - 1)); // Set the hours to day number minus 1
// multiplied by negative 24
alert(today); // will be Monday
Or as a function:
# modifies _date_
function setToMonday( date ) {
var day = date.getDay() || 7;
if( day !== 1 )
date.setHours(-24 * (day - 1));
return date;
}
setToMonday(new Date());
CMS's answer is correct but assumes that Monday is the first day of the week.
Chandler Zwolle's answer is correct but fiddles with the Date prototype.
Other answers that add/subtract hours/minutes/seconds/milliseconds are wrong because not all days have 24 hours.
The function below is correct and takes a date as first parameter and the desired first day of the week as second parameter (0 for Sunday, 1 for Monday, etc.). Note: the hour, minutes and seconds are set to 0 to have the beginning of the day.
function firstDayOfWeek(dateObject, firstDayOfWeekIndex) {
const dayOfWeek = dateObject.getDay(),
firstDayOfWeek = new Date(dateObject),
diff = dayOfWeek >= firstDayOfWeekIndex ?
dayOfWeek - firstDayOfWeekIndex :
6 - dayOfWeek
firstDayOfWeek.setDate(dateObject.getDate() - diff)
firstDayOfWeek.setHours(0,0,0,0)
return firstDayOfWeek
}
// August 18th was a Saturday
let lastMonday = firstDayOfWeek(new Date('August 18, 2018 03:24:00'), 1)
// outputs something like "Mon Aug 13 2018 00:00:00 GMT+0200"
// (may vary according to your time zone)
document.write(lastMonday)
First / Last Day of The Week
To get the upcoming first day of the week, you can use something like so:
function getUpcomingSunday() {
const date = new Date();
const today = date.getDate();
const currentDay = date.getDay();
const newDate = date.setDate(today - currentDay + 7);
return new Date(newDate);
}
console.log(getUpcomingSunday());
Or to get the latest first day:
function getLastSunday() {
const date = new Date();
const today = date.getDate();
const currentDay = date.getDay();
const newDate = date.setDate(today - (currentDay || 7));
return new Date(newDate);
}
console.log(getLastSunday());
* Depending on your time zone, the beginning of the week doesn't has to start on Sunday, it can start on Friday, Saturday, Monday or any other day your machine is set to. Those methods will account for that.
* You can also format it using toISOString method like so: getLastSunday().toISOString()
Check out Date.js
Date.today().previous().monday()
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 work well.
I'm using this
function get_next_week_start() {
var now = new Date();
var next_week_start = new Date(now.getFullYear(), now.getMonth(), now.getDate()+(8 - now.getDay()));
return next_week_start;
}
Returns Monday 00am to Monday 00am.
const now = new Date()
const startOfWeek = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay() + 1)
const endOfWeek = new Date(now.getFullYear(), now.getMonth(), startOfWeek.getDate() + 7)
This function uses the current millisecond time to subtract the current week, and then subtracts one more week if the current date is on a monday (javascript counts from sunday).
function getMonday(fromDate) {
// length of one day i milliseconds
var dayLength = 24 * 60 * 60 * 1000;
// Get the current date (without time)
var currentDate = new Date(fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate());
// Get the current date's millisecond for this week
var currentWeekDayMillisecond = ((currentDate.getDay()) * dayLength);
// subtract the current date with the current date's millisecond for this week
var monday = new Date(currentDate.getTime() - currentWeekDayMillisecond + dayLength);
if (monday > currentDate) {
// It is sunday, so we need to go back further
monday = new Date(monday.getTime() - (dayLength * 7));
}
return monday;
}
I have tested it when week spans over from one month to another (and also years), and it seems to work properly.
Good evening,
I prefer to just have a simple extension method:
Date.prototype.startOfWeek = function (pStartOfWeek) {
var mDifference = this.getDay() - pStartOfWeek;
if (mDifference < 0) {
mDifference += 7;
}
return new Date(this.addDays(mDifference * -1));
}
You'll notice this actually utilizes another extension method that I use:
Date.prototype.addDays = function (pDays) {
var mDate = new Date(this.valueOf());
mDate.setDate(mDate.getDate() + pDays);
return mDate;
};
Now, if your weeks start on Sunday, pass in a "0" for the pStartOfWeek parameter, like so:
var mThisSunday = new Date().startOfWeek(0);
Similarly, if your weeks start on Monday, pass in a "1" for the pStartOfWeek parameter:
var mThisMonday = new Date().startOfWeek(1);
Regards,
a more generalized version of this... this will give you any day in the current week based on what day you specify.
//returns the relative day in the week 0 = Sunday, 1 = Monday ... 6 = Saturday
function getRelativeDayInWeek(d,dy) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:dy); // adjust when day is sunday
return new Date(d.setDate(diff));
}
var monday = getRelativeDayInWeek(new Date(),1);
var friday = getRelativeDayInWeek(new Date(),5);
console.log(monday);
console.log(friday);
Simple solution for getting the first day of the week.
With this solution, it is possible to set an arbitrary start of week (e.g. Sunday = 0, Monday = 1, Tuesday = 2, etc.).
function getBeginOfWeek(date = new Date(), startOfWeek = 1) {
const result = new Date(date);
while (result.getDay() !== startOfWeek) {
result.setDate(result.getDate() - 1);
}
return result;
}
The solution correctly wraps on months (due to Date.setDate() being used)
For startOfWeek, the same constant numbers as in Date.getDay() can be used
setDate() has issues with month boundaries that are noted in comments above. A clean workaround is to find the date difference using epoch timestamps rather than the (surprisingly counterintuitive) methods on the Date object. I.e.
function getPreviousMonday(fromDate) {
var dayMillisecs = 24 * 60 * 60 * 1000;
// Get Date object truncated to date.
var d = new Date(new Date(fromDate || Date()).toISOString().slice(0, 10));
// If today is Sunday (day 0) subtract an extra 7 days.
var dayDiff = d.getDay() === 0 ? 7 : 0;
// Get date diff in millisecs to avoid setDate() bugs with month boundaries.
var mondayMillisecs = d.getTime() - (d.getDay() + dayDiff) * dayMillisecs;
// Return date as YYYY-MM-DD string.
return new Date(mondayMillisecs).toISOString().slice(0, 10);
}
Here is my solution:
function getWeekDates(){
var day_milliseconds = 24*60*60*1000;
var dates = [];
var current_date = new Date();
var monday = new Date(current_date.getTime()-(current_date.getDay()-1)*day_milliseconds);
var sunday = new Date(monday.getTime()+6*day_milliseconds);
dates.push(monday);
for(var i = 1; i < 6; i++){
dates.push(new Date(monday.getTime()+i*day_milliseconds));
}
dates.push(sunday);
return dates;
}
Now you can pick date by returned array index.
An example of the mathematically only calculation, without any Date functions.
const date = new Date();
const ts = +date;
const mondayTS = ts - ts % (60 * 60 * 24 * (7-4) * 1000);
const monday = new Date(mondayTS);
console.log(monday.toISOString(), 'Day:', monday.getDay());
const formatTS = v => new Date(v).toISOString();
const adjust = (v, d = 1) => v - v % (d * 1000);
const d = new Date('2020-04-22T21:48:17.468Z');
const ts = +d; // 1587592097468
const test = v => console.log(formatTS(adjust(ts, v)));
test(); // 2020-04-22T21:48:17.000Z
test(60); // 2020-04-22T21:48:00.000Z
test(60 * 60); // 2020-04-22T21:00:00.000Z
test(60 * 60 * 24); // 2020-04-22T00:00:00.000Z
test(60 * 60 * 24 * (7-4)); // 2020-04-20T00:00:00.000Z, monday
// So, what does `(7-4)` mean?
// 7 - days number in the week
// 4 - shifting for the weekday number of the first second of the 1970 year, the first time stamp second.
// new Date(0) ---> 1970-01-01T00:00:00.000Z
// new Date(0).getDay() ---> 4
It is important to discern between local time and UTC. I wanted to find the start of the week in UTC, so I used the following function.
function start_of_week_utc(date, start_day = 1) {
// Returns the start of the week containing a 'date'. Monday 00:00 UTC is
// considered to be the boundary between adjacent weeks, unless 'start_day' is
// specified. A Date object is returned.
date = new Date(date);
const day_of_month = date.getUTCDate();
const day_of_week = date.getUTCDay();
const difference_in_days = (
day_of_week >= start_day
? day_of_week - start_day
: day_of_week - start_day + 7
);
date.setUTCDate(day_of_month - difference_in_days);
date.setUTCHours(0);
date.setUTCMinutes(0);
date.setUTCSeconds(0);
date.setUTCMilliseconds(0);
return date;
}
To find the start of the week in a given timezone, first add the timezone offset to the input date and then subtract it from the output date.
const local_start_of_week = new Date(
start_of_week_utc(
date.getTime() + timezone_offset_ms
).getTime() - timezone_offset_ms
);
I use this:
let current_date = new Date();
let days_to_monday = 1 - current_date.getDay();
monday_date = current_date.addDays(days_to_monday);
// https://stackoverflow.com/a/563442/6533037
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
It works fine.
Accepted answer won't work for anyone who runs the code in UTC-XX:XX timezone.
Here is code which will work regardless of timezone for date only. This won't work if you provide time too. Only provide date or parse date and provide it as input. I have mentioned different test cases at start of the code.
function getDateForTheMonday(dateString) {
var orignalDate = new Date(dateString)
var modifiedDate = new Date(dateString)
var day = modifiedDate.getDay()
diff = modifiedDate.getDate() - day + (day == 0 ? -6:1);// adjust when day is sunday
modifiedDate.setDate(diff)
var diffInDate = orignalDate.getDate() - modifiedDate.getDate()
if(diffInDate == 6) {
diff = diff + 7
modifiedDate.setDate(diff)
}
console.log("Given Date : " + orignalDate.toUTCString())
console.log("Modified date for Monday : " + modifiedDate)
}
getDateForTheMonday("2022-08-01") // Jul month with 31 Days
getDateForTheMonday("2022-07-01") // June month with 30 days
getDateForTheMonday("2022-03-01") // Non leap year February
getDateForTheMonday("2020-03-01") // Leap year February
getDateForTheMonday("2022-01-01") // First day of the year
getDateForTheMonday("2021-12-31") // Last day of the year
Extending answer from #Christian C. Salvadó and information from #Ayyash (object is mutable) and #Awi and #Louis Ameline (set hours to 00:00:00)
The function can be like this
function getMonday(d) {
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
d.setDate(diff);
d.setHours(0,0,0,0); // set hours to 00:00:00
return d; // object is mutable no need to recreate object
}
getMonday(new Date())
Check out: moment.js
Example:
moment().day(-7); // last Sunday (0 - 7)
moment().day(7); // next Sunday (0 + 7)
moment().day(10); // next Wednesday (3 + 7)
moment().day(24); // 3 Wednesdays from now (3 + 7 + 7 + 7)
Bonus: works with node.js too

Detect last week of each month with javascript

what would be a way in javascript to detect the last week of each (current) month. Or last monday of the month?
I would suggest to get the number of days in the month and then loop from the last day until getDay() gives back a Monday (1) or Sunday(0) .. based on when does your week start. Once you get your start date ... end date would be startDate + 7 so something along these lines
I found this helpful :
//Create a function that determines how many days in a month
//NOTE: iMonth is zero-based .. Jan is 0, Feb is 2 and so on ...
function daysInMonth(iMonth, iYear)
{
return 32 - new Date(iYear, iMonth, 32).getDate();
}
Then the loop:
//May - should return 31
var days_in_month = daysInMonth(4, 2010);
var weekStartDate = null;
var weekEndDate = null;
for(var i=days_in_month; i>0; i--)
{
var tmpDate = new Date(2010, 4, i);
//week starting on sunday
if(tmpDate.getDay() == 0)
{
weekStartDate = new Date(tmpDate);
weekEndDate = new Date(tmpDate.setDate(tmpDate.getDate() + 6));
//break out of the loop
break;
}
}
Playing with the date object and its methods you can do the following..
update
the complete calculations to get to last monday of the month could be compacted to
var d = new Date();
d.setMonth( d.getMonth() + 1 );
d.setDate(0);
lastmonday = d.getDate() - (d.getDay() - 1);
alert(lastmonday);
verbose example..
var now = new Date(); // get the current date
// calculate the last day of the month
if (now.getMonth() == 11 ) // if month is dec then go to next year and first month
{
nextmonth = 0;
nextyear = now.getFullYear() + 1;
}
else // otherwise go to next month of current year
{
nextmonth = now.getMonth() + 1;
nextyear = now.getFullYear();
}
var d = new Date( nextyear , nextmonth , 0); // setting day to 0 goes to last date of previous month
alert( d.getDay() ); // will alert the day of the week 0 being sunday .. you can calculate from there to get the first day of that week ..
Use getDay() to get the day of week of the last day in month and work from that (substracting the value from the number of days of the month should probably do the trick. +/- 1).
To determine whether it is a Monday, use .getDay() == 1. To determine if it is the last of the month, add seven days and compare months: nextMonday.setDate(monday.getDate()+7);
nextMonday.getMonth() == monday.getMonth();
The Javascript "Date" object is your friend.
function lastOfThisMonth(whichDay) {
var d= new Date(), month = d.getMonth();
d.setDate(1);
while (d.getDay() !== whichDay) d.setDate(d.getDate() + 1);
for (var n = 1; true; n++) {
var nd = new Date(d.getFullYear(), month, d.getDate() + n * 7);
if (nd.getMonth() !== month)
return new Date(d.getFullYear(), month, d.getDate() + (n - 1) * 7).getDate();
}
}
That'll give you the date (in the month, like 30) of the last day of the month that's the chosen day of the week (0 through 7).
Finding the last week of the month will depend on what you mean by that. If you mean the last complete week, then (if you mean Sunday - Saturday) find the last Saturday, and subtract 6. If you mean the last week that starts in the month, find the last Sunday.
You may also like to find the third Monday or the first Tuesday before or after a given date,
or flag every Wednesday between two dates.
Date.prototype.lastweek= function(wd, n){
n= n || 1;
return this.nextweek(wd, -n);
}
Date.prototype.nextweek= function(wd, n){
if(n== undefined) n= 1;
var incr= (n<0)? 1: -1,
D= new Date(this),
dd= D.getDay();
if(wd=== undefined) wd= dd;
if(dd!= wd) while(D.getDay()!= wd) D.setDate(D.getDate()+incr);
D.setDate(D.getDate()+7*n);
D.setHours(0, 0, 0, 0);
return D;
}
function lastMondayinmonth(month, year){
var day= new Date();
if(!month) month= day.getMonth()+1;
if(!year) year= day.getFullYear();
day.setFullYear(year, month, 0);
return day.lastweek(1);
}
alert(lastMondayinmonth())
i found such example that detects last monday of each week but it wont detect last monday of the month. maybe it will help to find better solution, that code looks short.
var dif, d = new Date(); // Today's date
dif = (d.getDay() + 6) % 7; // Number of days to subtract
d = new Date(d - dif * 24*60*60*1000); // Do the subtraction
alert(d); // Last monday.
OK, so far i came up with such solution making it a bit of my own way and getting a few things mentioned here. It works correct and always returns the last monday of current month.
//function that will help to check how many days in month
function daysInMonth(iMonth, iYear)
{
return 32 - new Date(iYear, iMonth, 32).getDate();
}
var dif = null;
d = new Date(); // Today's date
countDays = daysInMonth(d.getMonth(),d.getFullYear()); //Checking number of days in current month
d.setDate(countDays); //setting the date to last day of the month
dif = (d.getDay() + 6) % 7; // Number of days to subtract
d = new Date(d - dif * 24*60*60*1000); // Do the subtraction
alert(d.getDate()); //finally you get the last monday of the current month
Get the last day of the month:
/**
* Accepts either zero, one, or two parameters.
* If zero parameters: defaults to today's date
* If one parameter: Date object
* If two parameters: year, (zero-based) month
*/
function getLastDay() {
var year, month;
var lastDay = new Date();
if (arguments.length == 1) {
lastDay = arguments[0];
} else if (arguments.length > 0) {
lastDay.setYear(arguments[0]);
lastDay.setMonth(arguments[1]);
}
lastDay.setMonth(lastDay.getMonth() + 1);
lastDay.setDate(0);
return lastDay;
}
Get the last Monday:
/**
* Accepts same parameters as getLastDay()
*/
function getLastMonday() {
var lastMonday = getLastDay.apply(this, arguments);
lastMonday.setDate(lastMonday.getDate() - (lastMonday.getDay() == 0 ? 6 : (lastMonday.getDay() - 1)));
return lastMonday;
}
Get week of the year for a given day:
/**
* Accepts one parameter: Date object.
* Assumes start of week is Sunday.
*/
function getWeek(d) {
var jan1 = new Date(d.getFullYear(), 0, 1);
return Math.ceil((((d - jan1) / (24 * 60 * 60 * 1000)) + jan1.getDay() + 1) / 7);
}
Putting them together (assuming you're using Firebug):
// Get the last day of August 2006:
var august2006 = new Date(2006, 7);
var lastDayAugust2006 = getLastDay(august2006);
console.log("lastDayAugust2006: %s", lastDayAugust2006);
// ***** Testing getWeek() *****
console.group("***** Testing getWeek() *****");
// Get week of January 1, 2010 (Should be 1):
var january12010Week = getWeek(new Date(2010, 0, 1));
console.log("january12010Week: %s", january12010Week);
// Get week of January 2, 2010 (Should still be 1):
var january22010Week = getWeek(new Date(2010, 0, 2));
console.log("january22010Week: %s", january22010Week);
// Get week of January 3, 2010 (Should be 2):
var january32010Week = getWeek(new Date(2010, 0, 3));
console.log("january32010Week: %s", january32010Week);
console.groupEnd();
// *****************************
// Get the last week of this month:
var lastWeekThisMonth = getWeek(getLastDay());
console.log("lastWeekThisMonth: %s", lastWeekThisMonth);
// Get the last week of January 2007:
var lastWeekJan2007 = getWeek(getLastDay(2007, 0));
console.log("lastWeekJan2007: %s", lastWeekJan2007);
// Get the last Monday of this month:
var lastMondayThisMonth = getLastMonday();
console.log("lastMondayThisMonth: %s", lastMondayThisMonth);
// Get the week of the last Monday of this month:
var lastMondayThisMonthsWeek = getWeek(lastMondayThisMonth);
console.log("lastMondayThisMonthsWeek: %s", lastMondayThisMonthsWeek);

Categories

Resources