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

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 ;

Related

start week day from sunday - javascript

I want to retrieve a date by providing day number of a specific week
E.g
When I say
day: 1
It should provide me:
2023-01-15
What I have tried so far is:
function calculatedDate (day){
let date = new Date();
let dayAtDate = date.getDay();
let dayDiff = day - dayAtDate;
if(dayDiff < 0){
dayDiff = 7 + dayDiff;
}
let desiredDate = date.setDate(date.getDate() + dayDiff);
return new Date(desiredDate);
}
console.log(calculatedDate(1));
Now the problem with above code is that it considers day: 1 as monday, but I want day: 1 to be sunday here.
Can anyone help me with the best possible way here?
How about just -1 the provided day? that should solve it:
function calculatedDate (day){
let date = new Date();
let dayAtDate = date.getDay();
day = day - 1;
let dayDiff = day - dayAtDate;
if(dayDiff < 0){
dayDiff = 7 + dayDiff;
}
let desiredDate = date.setDate(date.getDate() + dayDiff);
return new Date(desiredDate);
}
console.log(calculatedDate(1));
You'd probably want to add some validation on the input parameter day, make sure it's a number and 1 or greater.
The current day will be 0, account for this by making the following change.
if(dayDiff < 0){
dayDiff = 6 + dayDiff;
}
Sunday is 0, Monday is 1 here :
function calculatedDate (day) {
let date = new Date();
let dayAtDate = date.getDay();
let dayDiff = day - (dayAtDate + 1); // change here
if (dayDiff < 0) {
dayDiff = 7 + dayDiff;
}
let desiredDate = date.setDate(date.getDate() + dayDiff);
return new Date(desiredDate);
}
console.log(calculatedDate(1));

How to find 2nd and 4th Saturday in js Fullcalender?

How I can find second and fourth Saturday in JavaScript fullcalender api, so that I can highlight those 2nd and 4th Saturday with "week Day Off" event name?
Fullcalendar_screenshot
You need to find all saturdays in current month. Then filter by odd index since 2th and 4th are 1 and 3 indexes.
Now you can highlight day that matched.
function getSaturdays(year, month) {
let day, date;
let saturdays = [];
day = 1;
date = new Date(year, month, day);
while (date.getMonth() === month) {
if (date.getDay() === 6) { // Sun=0, Mon=1, Tue=2, etc.
saturdays.push(new Date(year, month, day).getDate());
}
day += 1;
date = new Date(year, month, day);
}
return saturdays;
}
let saturdays = getSaturdays(2021, 5).filter((day, index) => index % 2 !== 0)
console.log(saturdays)
Original answer
//Here instead of arrayOfDaysInMonth variable you can pass javascript dates according to month here i have passed statically
var arrayOfDaysInMonth = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28];//feb
var saturdays = [2,4] // 2nd and 4th saturday;
var secondWeekOfCount = [];
var whichDateIsSecondorFourthSat=[];
arrayOfDaysInMonth.map((i)=>{
var myDate = new Date();
myDate.setFullYear(2022);
myDate.setMonth(1); // Feb
myDate.setDate(i);
if(myDate.getDay() === 6){
secondWeekOfCount.push(i);
saturdays.map((d)=>{
if(d ===secondWeekOfCount.length ){
whichDateIsSecondorFourthSat.push(i)
}
})
}
})
console.log(whichDateIsSecondorFourthSat)// This will be your result

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 for getting the previous Monday

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

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