Change the displayed date once a week using javascript - javascript

I would like to show the date in an element on a web page, then once a week on a Saturday it will update to that Saturdays date, if the Saturday of the week hasn't been reached it will simply display the previous Saturdays date until the next Saturday.
I am able to get the date and to extract the day of the week, therefore i can identify when it is a Saturday. I have attempted to include an IF statement that will update the text when Saturday arrives. That seems to be working however I do not know how to keep it displaying the previous Saturdays date until it next updates?
HTML:
<div id="date">
</div>
JS:
var date = new Date(); //Gets current date
var day = date.getDay(); //Isolates what day it is
if (day === 6) {
document.getElementById("date").innerHTML = date;
} else {
//keep the previous saturday somehow?
}
I have a JSFiddle with the code I have been practising with:
https://jsfiddle.net/Lime26/8txryo3k/13/
Seems to be working what I have so far, not sure how to get it to continue displaying the previous Saturdays date.
On a side note: to test this I have been manually changing the day integer between 0 and 6 to determine if it is working which it is.
I am attempting to set the date by entering 6, then I will enter a different number and in theory I would like it to not change (to check it I am watching the seconds and minutes expecting them to remain 'frozen') and then when I enter 6 again I expect it to change to the most current time.

this solution no need if condition:
var date = new Date(); //Gets current date
var day = date.getDay(); //Isolates what day it is
date.setDate(date.getDate() - (day+1) % 7 );
// day = 0 , (day+1) % 7 = 1
// day = 1 , (day+1) % 7 = 2
// .
// .
// day = 6 , (day+1) % 7 = 0 /here is sat
document.getElementById("date").innerHTML = date;
<div id="date"></div>

This uses the MomentJS library. The library has additional formatting options, this is just one example.
const saturday = moment().day(6);
const saturdayFormatted = moment(saturday).format("ddd MM/DD/YYYY");
const prevSaturday = moment().day(13);
const prevSaturdayFormatted = moment(prevSaturday ).format("ddd MM/DD/YYYY");
const e1 = document.getElementById("id1").innerHTML = saturday;
const e2 = document.getElementById("id2").innerHTML = saturdayFormatted
const e3 = document.getElementById("id3").innerHTML = prevSaturday;
const e4 = document.getElementById("id4").innerHTML = prevSaturdayFormatted;
<script src="https://momentjs.com/downloads/moment.js"></script>
This Saturday (with and without formatting)
<ul>
<li id="id1">one</li>
<li id="id2">two</li>
</ul>
Next Saturday (with and without formatting)
<ul>
<li id="id3">one</li>
<li id="id4">two</li>
</ul>

This will do the trick.
I'm essentially converting the current time into a Unix timestamp (epoch time) and subtracting the number of days that have passed in seconds. This will give you back the same time but the date turned back.
var date = new Date();
var day = date.getDay();
if (day === 6) {
document.getElementById("date").innerHTML = date;
} else {
date.setTime(date.getTime() - (86400 * ((day % 6) + 1)));
document.getElementById("date").innerHTML = date;
}
<span id="date"></span>

Related

How to display today's date and time as 9 am and continue till next day?

I am doing a react project.I want to display today's date and time as "9 am" .This has to be remained unchanged till time is 9 am on next day. After that it should display time as 9 am along with date of that day and continue this till next day 9 am and so on.
<span>Last Updated: {moment().format('MMMM Do YYYY,') + " 9:00 am"}</span>
The above code displays the time as 9 am even before the time is 9 am on the nextday. It should look like current time and date gets updated only at 9 am everyday.
This code creates a function that retrieves the formatted date at a given hour. If the hour is not specified, it will use the current hour. It will return today's date, unless the hour is before 9, in which case it will return yesterday's date. The format will use the current user's native formatting for a "long" date. The HTML shows the desired result, the console logs what happens before 9 on the current day, and the current hour. The hour is determined by the user's time zone.
function getDateAtNine(forceHour) {
let now = new Date();
const hour = forceHour == null ? now.getHours() : forceHour;
if (hour < 9) {
now = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
}
return new Intl.DateTimeFormat(undefined, {
dateStyle: 'long'
}).format(now);
}
console.log(getDateAtNine(8)); // shows what will print at 8 am on today's date
console.log(getDateAtNine()); // shows what will print at the current hour on today's date
document.querySelector('#dateat9').textContent = getDateAtNine();
<span id="dateat9"></span><span id="nineam">, 9:00 am</span>
Is that what you are looking for? ;)
const getLastStartOfDay = (startOfDayHour) => {
let todayStartOfDay = new Date();
todayStartOfDay.setHours(startOfDayHour, 0, 0, 0);
let yesterdayStartOfDay = new Date(todayStartOfDay);
yesterdayStartOfDay.setDate(yesterdayStartOfDay.getDate() - 1);
let dt = new Date();
const displayDate =
dt.getHours() < startOfDayHour ? yesterdayStartOfDay : todayStartOfDay;
return displayDate;
};
console.log("LastStartOfDay: ", getLastStartOfDay(9));

Momentjs - Week Numbers When April Is Week One

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

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;
}
};

Looking to add 1 month to current date inside a div

i am looking to display the date plus 1 month inside a div which will be used to display next invoice date. i have seen a few examples in various places, but could not implement. I also saw that there were many solutions, and some controversy surrounding each one.
Once you have a date object, just call setMonth(), passing in the current number of months plus 1.
var CurrentDate = new Date();
CurrentDate.setMonth(CurrentDate.getMonth() + 1);
You can either use this : http://jsfiddle.net/dfA8b/ if you need same date of the next month
var invoiceDt = new Date();
invoiceDt.setMonth(invoiceDt.getMonth()+1);
$('#invoiceDate').text(invoiceDt.toDateString());
Or
You can use this : http://jsfiddle.net/hjSDu/ if you need 30 days month(mostly used for invoice purposes)
var invoiceDt = new Date();
var days = 30;
invoiceDt.setDate(invoiceDt.getDate()+days);
$('#invoiceDate').text(invoiceDt.toDateString());
For the formatting purpose :
http://jsfiddle.net/7bU6n/
var invoiceDt = new Date();
invoiceDt.setMonth(invoiceDt.getMonth()+1);
$('#invoiceDate').text((invoiceDt.getMonth()+1) +"-"+ invoiceDt.getDate() +"-" + invoiceDt.getFullYear());
also see : https://stackoverflow.com/a/1643468/3603806
1 month is not so clear... what You mean? 31, 30 days or if exists simply same date of the following month?
1st case: (assuming 31 days)
var d = new Date(),
dplus31 = d.getDate() + 31;
d.setDate(dplus31);
console.debug(d, dplus31);
2nd case: one month
var d = new Date(),
dplus1 = d.getMonth() + 1;
d.setMonth(dplus1);
console.debug(d, dplus1);
..but even in this case there are some edge cases (ex. 31 January)
hope it helps
function addMonthsNoOverflow(dateParam, intParam) {
var sum = new Date(new Date(dateParam.getTime()).setMonth(dateParam.getMonth() + intParam);
if (sum.getDate() < dateParam.getDate()) { sum.setDate(0); }
return(sum);
}
Notes:
It handles cases where 29, 30 or 31 turned into 1, 2, or 3 by eliminating the overflow
Day of Month is NOT zero-indexed so .setDate(0) is last day of prior month.

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

Categories

Resources