JavaScript for getting the previous Monday - javascript

I would like for the previous Monday to appear in the field where a user enters today's date.
E.g.: If today's date is entered 29-Jan-16 then the code would make the previous Monday's date to appear instead (which would be 25-Jan-16).
I have seen some code online:
function getPreviousMonday() {
var date = new Date();
if (date.getDay() != 0) {
return new Date().setDate(date.getDate() - 7 - 6);
} else {
return new Date().setDate(date.getDate() - date.getDate() - 6);
}
}
However, this is not quite working, why?

var prevMonday = new Date();
prevMonday.setDate(prevMonday.getDate() - (prevMonday.getDay() + 6) % 7);
I am a little late but I like this solution. It's a one liner and not that complicated. Making a function for that seems overkill to me.

I think your math is just a little off, and I tidied your syntax;
function getPreviousMonday()
{
var date = new Date();
var day = date.getDay();
var prevMonday = new Date();
if(date.getDay() == 0){
prevMonday.setDate(date.getDate() - 7);
}
else{
prevMonday.setDate(date.getDate() - (day-1));
}
return prevMonday;
}
That way you always get the last Monday that happened (which is 7 days ago if today is Monday)

Based on #Philippe Dubé-Tremblay answer, i wanted to come up with something that lets you target any previous day:
let target = 1 // Monday
let date = new Date()
date.setDate(date.getDate() - ( date.getDay() == target ? 7 : (date.getDay() + (7 - target)) % 7 ))
This takes into account the previous Monday if today is also Monday

Using moment.js:
moment().day("Monday").format('YYYY-MM-DD');

Thank you #Philippe Dubé-Tremblay for your nice solution (above),
I will just put here the wrapping function for those who, like me, plan to call this function repeatedly.
// Accepts a date as parameter or with no parameter will assume the current date.
const getPreviousMonday = (date = null) => {
const prevMonday = date && new Date(date.valueOf()) || new Date()
prevMonday.setDate(prevMonday.getDate() - (prevMonday.getDay() + 6) % 7)
return prevMonday
}

Here is a fiddle demonstrating a few different formats: https://jsfiddle.net/umefez2j/3/
function getMonday(d) {
var m_names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
//Use this one to return this format: Mon Jan 25 2016 09:37:51 GMT-0600 (Central Standard Time)
//return new Date(d.setDate(diff));
//Use this one to return this format: Mon, 25 Jan 2016
//monday=new Date(d.setDate(diff)).toUTCString();
//monday=monday.split(' ').slice(0, 4).join(' ')
//return monday;
//Use this one to return this format: 25-Jan-2016
monday=new Date(d.setDate(diff));
var curr_date = monday.getDate();
var curr_month = monday.getMonth();
var curr_year = monday.getFullYear();
return curr_date + "-" + m_names[curr_month] + "-" + curr_year;
}
alert(getMonday(new Date()));
//Created with help from:
//http://stackoverflow.com/a/27480352/3112803
//http://stackoverflow.com/a/4156516/3112803
//http://stackoverflow.com/a/27869948/3112803

The above solutions didn't work for me.
In #Philippe Dubé-Tremblay's solution, it will return the same day if today is already monday!
function getPreviousMonday() : Date {
let date = new Date();
let day = date.getDay();
let prevMonday = new Date();
if(day == 0 || day == 1){
prevMonday.setDate(date.getDate() - (day + 6));
}
else{
prevMonday.setDate(date.getDate() - (day - 1));
}
return prevMonday;
}
OR
if (day == 1) {
prevMonday.setDate(date.getDate() - 7);
}
else {
prevMonday.setDate(date.getDate() - (day + 6) % 7);;
}
This works for me!

Here is my code to get the last monday from a given date. If the given date is a monday, it returns the same day. This can be used to get the monday of the week that the date is on
let currDate = new Date();
let lastMonday = new Date();
let daysDiff = currDate.getDay() - 1;
lastMonday.setDate(currDate.getDate() - (daysDiff > 0 ? daysDiff : (daysDiff * -6)));

The easiest solution is to go back the number of days based on today's date. For example, if today's day(0) is Sunday, you can go back 6 days to find the previous Monday. If Today is Monday, you can go back 7 days. Therefore using a modulo will help you in this scenario simply because the number of days you will need to go back is %7 plus 6.
Let me break it down in simple steps.
var today=new Date();
This will give you today's date. Now,
var todaysDay=today.getDay();
This will give you your day starting with zero.
var goBack=today.getDay()%7+6;
Now, declare a new date.
var lastMonday=new Date().setDate(today.getDate()-goBack);
Now, this will give you a numeric date value. Convert it back to Date
var desiredDate=new Date(lastMonday);

Related

Javascript how to get full two year from current month?

I have question about getting full two years from the current date. So what i did id get the current month using the new date function and used the for loop to print each of the month. But, i cant really get it to work.... I will post the code that i did below. I would be really appreciate it if anyone can tell me the logic or better way of doing it.
For example: if today current date is august it store into an array from 8 / 2020 9/ 2020 ..... 12/ 2020, 1/2021 and goes to another year to 8/2022.
var d = new Date();
var year = d.getFullYear();
var dateStr;
var currentYear;
var storeMonthYear = [];
for(var i = 1; i <= 24; i++){
dateStr = d.getMonth() + i
currentYear = year;
if(dateStr > "12"){
dateStr = dateStr - 12
// currentYear = year;
// if(currentYear){
// }
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else if(dateStr > "24"){
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else{
storeMonthYear[i] = dateStr + "/" + currentYear;
}
storeMonthYear[i] = d.getMonth() + i
}
export const settlementPeriod = [
{
MonthYearFirstRow1: storeMonthYear[1],
MonthYearFirstRow2: storeMonthYear[2],
MonthYearFirstRow3: storeMonthYear[3],
MonthYearFirstRow4: storeMonthYear[4],
MonthYearFirstRow5: storeMonthYear[5],
MonthYearFirstRow6: storeMonthYear[6],
MonthYearFirstRow7: storeMonthYear[7],
MonthYearFirstRow8: storeMonthYear[8],
MonthYearFirstRow9: storeMonthYear[9],
MonthYearFirstRow10: storeMonthYear[10],
MonthYearFirstRow11: storeMonthYear[11],
MonthYearFirstRow12: storeMonthYear[12],
MonthYearSecondRow13: storeMonthYear[13],
MonthYearSecondRow14: storeMonthYear[14],
MonthYearSecondRow15: storeMonthYear[15],
MonthYearSecondRow16: storeMonthYear[16],
MonthYearSecondRow17: storeMonthYear[17],
MonthYearSecondRow18: storeMonthYear[18],
MonthYearSecondRow19: storeMonthYear[19],
MonthYearSecondRow20: storeMonthYear[20],
MonthYearSecondRow21: storeMonthYear[21],
MonthYearSecondRow22: storeMonthYear[22],
MonthYearSecondRow23: storeMonthYear[23],
MonthYearSecondRow24: storeMonthYear[24]
},
];
Create the date from today, get the month and year. Iterate from 0 to 24 for now till in 24 months. If month is 12 than set month to 0 and increment the year. Push the new datestring. Increment the month for the next step.
Note: Beacsue JS counts months form 0-11 you had to add for the datestring 1 for the month and make the change of year at 12 and not 13.
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth();
let res=[];
for (let i=0; i<=24; i++) {
if (month===12) {
month = 0;
year++;
}
res.push(month+1 + '/' + year);
month++;
}
console.log(res);
Here you go, you get an array of strings like "8/2020","9/2020" etc from starting month to the last month including both( in total 25 months).
If you don't want to include last month just delete +1 from for loop condition.
let currentDate = new Date();
let settlementPeriod = [];
let numberOfMonths = 24;
for(let i=0;i<numberOfMonths+1;i++){
settlementPeriod.push(currentDate.getMonth()+1+"/"+currentDate.getFullYear()); //We add current date objects attributes to the array
currentDate = new Date(currentDate.setMonth(currentDate.getMonth()+1)); //Every time we add one month to it
}
console.log(settlementPeriod);
There are a couple of things that stick out in your code sample:
You're comparing strings and numbers (e.g. dateStr > "12"). This will lead to some weird bugs and is one of JS's most easily misused "features". Avoid it where possible.
You increment the year when you reach 12 months from now, rather than when you reach the next January
You're overwriting your strings with this line storeMonthYear[i] = d.getMonth() + i so your array is a bunch of numbers rather than date strings like you expect
Here's a code sample that I think does what you're expecting:
function next24Months() {
const today = new Date()
let year = today.getFullYear()
let monthIndex = today.getMonth()
let dates = []
while (dates.length < 24) {
dates.push(`${monthIndex + 1}/${year}`)
// increment the month, and if we're past December,
// we need to set the year forward and the month back
// to January
if (++monthIndex > 11) {
monthIndex = 0
year++
}
}
return dates
}
In general, when you're dealing with dates, you're probably better off using a library like Moment.js - dates/times are one of the most difficult programming concepts.
While #Ognjen 's answer is correct it's also a bit waseful if your date never escapes its function.
You don't need a new date every time:
function getPeriods(firstMonth, numPers){
var d = new Date(firstMonth.getTime()); // clone the start to leave firstMonth alone
d.setDate(1); // fix after #RobG
var pers = [];
var m;
for(var i = 0; i< numPers; i++){
m = d.getMonth();
pers.push(`${m+ 1}/${d.getFullYear()}`)
d.setMonth(m + 1); // JS dates automatically roll over. You can do this with d.setDate() as well and when you assign 28, 29, 31 or 32 the month and year roll over automatically
}
return pers;
}

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

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

Javascript : Get the first day of the week passing the current date

We have requirement that we need to pass the current date and get the start date of the week. While doing this the start day is user defined like if the user defines the start day as 0 ,day of the week will be sunday,if 1 then start day will be monday and like wise..
We tried the solution from the link Start day of the Week
But it only handles monday or sunday.
I tried the following code but it will fail select friday or saturday ,it will break
var startDate = 5;
if (!d) return;
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day;
var sunday = new Date(d.setDate(diff));
//add days to sunday to adjust sunday,monday,tue,wed...
return new Date(sunday.getYear(), sunday.getMonth(),sunday.getDate()-(7-startDate));
Let me know if any one has idea to do this.
Thanks.
function getStartOfWeek(index) {
var d = new Date();
var day = d.getDay();
var diff = index - day;
if(index > day) {
diff -= 7;
}
return new Date(d.setDate(d.getDate() + diff));
}
document.write(getStartOfWeek(0).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(1).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(2).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(3).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(4).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(5).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(6).toLocaleDateString()+"<br/>");
This is my "home-made" solution :
getWeekStartDate = function(date)
{
var d = new Date(date);
// Sunday
if (date.getDay() === 0)
return new Date(d.setDate(date.getDate()-6));
// Monday
if (date.getDay() === 1)
return date;
return new Date(d.setDate(date.getDate() - (date.getDay() - 1)));
};
I work with Date objects but of course you can get the day you were looking for with date.getDay()
Hope it helps
I have tried in Jquery and found the solution. Below is the code. It works good.
$first_day_of_the_week = 'Monday';
$start_of_the_week = date('Y-m-d',strtotime("Last $first_day_of_the_week"));
if ( strtolower(date('l')) === strtolower($first_day_of_the_week) )
{
$start_of_the_week = date('Y-m-d',strtotime('today'));
}
echo $start_of_the_week ;

Using Javascript to automatically adjust date to 2nd Saturday of every month?

I need Javascript code for a website to automatically adjust a date. The goal is to have the code automatically adjust the following statement to be the second Saturday of every month from now until eternity:
Next membership meeting: Saturday, MONTH, DAY, YEAR 11 a.m. to noon.
Anyone have an idea? Much appreciated!
This function will get you the date object, you can pull out what you need from it:
var getMeeting = function(year, month){
var date = new Date(year, month, 1, 0, 0, 0, 0);
date.setDate(14-date.getDay());
return date;
};
alert(getMeeting(2011,5));
I didn't test but here is the basics:
//our main code
var Months = ["Jan", "Feb", "Mar", /*... you finish... */ ];
var meetingDate = getMonthlyMeeting();
document.Write( "<i>Next membership meeting:</i> Saturday, " + Months[meetingDate.getMonth()] + ", " + meetingDate.getDay() + ", " + meetingDate.getYear() + " 11 a.m. to noon.");
// call this to get the monthly meeting date
// returns a Date() object
function getMonthlyMeeting(){
var today = new Date(); //JS automatically initializes new Date()s to the current time
//first, see if today is our meeting day
var meetingDate;
var thisMonthsMeeting = getSecondTuesdayInMonth(today.getMonth(), today.getYear());
if( thisMonthsMeeting.getDay() == today.getDay() ){
// today is our meeting day!
meetingDate = today;
}
else {
if ( today.getDay() < thisMonthsMeeting.getDay() ){
// it hasn't happened this month yet
meetingDate = thisMonthsMeeting;
} else {
//this month's meeting day has already passed
if( today.getMonth() == 11 ){
// rolling over to the next year
meetingDate = getSecondTuesdayInMonth(0, today.getYear() + 1);
} else {
meetingDate = getSecondTuesdayInMonth(today.getMonth() + 1, today.getYear());
}
}
}
return meetingDate;
}
// this is a helper function to get the second tuesday in any month
// returns a Date() object
function getSecondTuesdayInMonth(var month, var year){
var saturdays = 0;
var testDay= new Date();
while( testDay.getDay() != 2 && saturdays < 2 ){
//while the day we are testing isnt tuesday (2) and we haven't found it twice
if( testDay.getDay() == 2 )
saturdays = saturdays + 1; //we found a saturday
testDay= new Date(testDay.getTime() + 86400000); //increment our day to the next day
}
//when we finish the while loop, we are on our day
return testDay;
}
So, I figure that the meat of your problem is: How do I know what the second saturday of each month is?
Not tested, but this is what I came up with:
It is abstracted for any nth day of any month.
nthDate = function(nth_week, nth_day, month){
var src_date = new Date();
src_date.setDate(1);
src_date.setMonth(month);
return ( (nth_week * 7) - src_date.getDay() ) - ( Math.abs( nth_day - 6) );
};
var cur_date = new Date();
var cur_day = cur_date.getDay();
//2 for the 2nd week of the month
//6 is the integer value for saturday (days of the week 0-6)
var nth_date = nthDate( 2, 6, cur_date.getMonth() );
if(cur_day < nth_date){
//display the upcoming date here
}else if( cur_day > nth_date){
//figure out next month's date and display that
var next_date = nthDate(2, 6, (cur_date.getMonth() +1) );
//does this deal with the case of the month being december?? not sure.
}
The 2nd week is in the range of 14 days into the month.
We can:
first subtract the offset for the day of the week that this month starts with,
then second:
we can subtract the offset for the day of the week that we are looking for.
(this needs to be the offset of days, so saturday is a 0 (zero) offset. We get this value from the absolute value of nth day minus the number of days in the week.
This gives us the date of the second saturday.
Then, because you have some ints you can do a simple compare against the values.
If we're before the second saturday, display that, if not calculate a new date for next month.
Hope that helps.

How do I get the first day of the previous week from a date object in JavaScript?

given a date object,how to get previous week's first day
This Datejs library looks like it can do that sort of thing relatively easily.
Code:
function getPreviousSunday()
{
var today=new Date();
return new Date().setDate(today.getDate()-today.getDay()-7);
}
function getPreviousMonday()
{
var today=new Date();
if(today.getDay() != 0)
return new Date().setDate(today.getDate()-7-6);
else
return new Date().setDate(today.getDate()-today.getDay()-6);
}
Reasoning:
Depends what you mean by previous week's first day. I'll assume you mean previous sunday for the sake of this discussion.
To find the number of days to subtract:
Get the current day of the week.
If the current day of the week is Sunday you subtract 7 days
If the current day is Monday you subtract 8 days
...
If the current day is Saturday 13 days
The actual code once you determine the number of days to subtract is easy:
var previous_first_day_of_week=new Date().setDate(today.getDate()-X);
Where X is the above discussed value. This value is today.getDay() + 7
If by first day of the week you meant something else, you should be able to deduce the answer from the above steps.
Note: It is valid to pass negative values to the setDate function and it will work correctly.
For the code about Monday. You have that special case because getDay() orders Sunday before Monday. So we are basically replacing getDay() in that case with a value of getDay()'s saturday value + 1 to re-order sunday to the end of the week.
We use the value of 6 for subtraction with Monday because getDay() is returning 1 higher for each day than we want.
function previousWeekSunday(d) {
return new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay() - 7);
}
function previousWeekMonday(d) {
if(!d.getDay())
return new Date(d.getFullYear(), d.getMonth(), d.getDate() - 13);
return new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay() - 6);
}
I didn't quite understand other people's posts. Here is the javascript I use to display a Sun-Sat week relative to a given day. So, for instance, to get "last week," you're checking what the Sun/Sat goalposts were relative to seven days ago: new Date()-7
// variables
var comparedate = new Date()-7; // a week ago
var dayofweek = comparedate.getDay();
// just for declaration
var lastdate;
var firstadate;
// functions
function formatDate (dateinput) // makes date "mm/dd/yyyy" string
{
var month = dateinput.getMonth()+1;
if( month < 10 ) { month = '0' + month }
var date = dateinput.getDate();
if( date < 10 ) { var date = '0' + date }
var dateoutput = month + '/' + date + '/' + dateinput.getFullYear();
return dateoutput;
}
// Sunday to Saturday ... Sunday is the firstdate, Saturday is the lastdate
// (modify this block if you want something different eg: Monday to Sunday)
if ( dayofweek == 6 ) { lastdate = comparedate; firstdate = comparedate-6; } // Saturday
else if ( dayofweek == 0 ) { lastdate = comparedate+6; firstdate = comparedate; } // Sunday
else if ( dayofweek == 1 ) { lastdate = comparedate+5; firstdate = comparedate-1; } // Monday
else if ( dayofweek == 2 ) { lastdate = comparedate+4; firstdate = comparedate-2; } // Tuesday
else if ( dayofweek == 3 ) { lastdate = comparedate+3; firstdate = comparedate-3; } // Wednesday
else if ( dayofweek == 4 ) { lastdate = comparedate+2; firstdate = comparedate-4; } // Thursday
else if ( dayofweek == 5 ) { lastdate = comparedate+1; firstdate = comparedate-5; } // Friday
// Finish
var outputtowebpage = formatDate(firstdate) + ' - ' + formatDate(lastdate);
document.write(outputtowebpage);
I have to look this up every time I need to do it. So, I hope this is helpful to others.
First day of week can be either Sunday or Monday depending on what country you are in:
function getPrevSunday(a) {
return new Date(a.getTime() - ( (7+a.getDay())*24*60*60*1000 ));
};
function getPrevMonday(a) {
return new Date(a.getTime() - ( (6+(a.getDay()||7))*24*60*60*1000 ));
};
If you want to set a dateobject to the previous sunday you can use:
a.setDate(a.getDate()-7-a.getDay());
and for the previous monday:
a.setDate(a.getDate()-6-(a.getDay()||7));
In the other examples you will have a problem when sunday falls in other month. This should solve the problem:
var today, todayNumber, previousWeek, week, mondayNumber, monday;
today = new Date();
todayNumber = today.getDay();
previousWeek = -1; //For every week you want to go back the past fill in a lower number.
week = previousWeek * 7;
mondayNumber = 1 - todayNumber + week;
monday = new Date(today.getFullYear(), today.getMonth(), today.getDate()+mondayNumber);

Categories