Get last 7 days by names javascript - javascript

How to get the last seven days, from today, (by names) in java script.
like if today is Wednesday, I want to get it like (Wednesday, Tuesday, Monday, Sunday, Saturday, Friday, Thursday, Wednesday).

Just add the days in the string array and iterate them backward by getting current date with new Date() this will return the index of current day
const weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const d = new Date();
let day = weekday[d.getDay()];
var wanteddays = 8;
var temp = d.getDay()
while(wanteddays!=0){
if (temp <0)
temp = 6;
console.log(weekday[temp]);
temp = temp-1;
wanteddays = wanteddays -1;
}

function getDayName(date, len, local) {
let newDate = new Date(date);
let weekDays = [];
Array(len).fill(1).forEach((subDay) => {
newDate.setDate(newDate.getDate() - subDay);
weekDays.push(newDate.toLocaleDateString(local, { weekday: 'long' }));
})
return weekDays;
}
to use:
getDayName(Date.now(), 7, 'en-EN')
OR
getDayName('10/12/2022', 7, 'en-EN')
Typescript:
function getDayName(date: Date | string | number, len: number, local:string) {
let newDate = new Date(date);
let weekDays: string[] = [];
Array(len).fill(1).forEach((subDay: number) => {
newDate.setDate(newDate.getDate() - subDay);
weekDays.push(newDate.toLocaleDateString(local, { weekday: 'long' }));
})
return weekDays;
}

This should order an array to follow your wished output.
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var currentDay = days[ (new Date()).getDay()]
days = days.reverse();
var x = days.indexOf(currentDay)
var daysLastSeven = days.slice(x).concat(days.slice(0,x))
console.log(daysLastSeven)

Related

Create days array from Today till seven days ago with date-fns

In my React component, I have to render a list of days: from Today - seven days ago.
Like: Today / Yesterday / Monday / Tuesday / Wednesday / Thursday / Friday.
I am using date-fns.
const generateDays = () => {
const date: Date = new Date();
const a = subDays(date, 4);
const formatted = format(a, 'eeee', { locale: nl });
return formatted;
};
How do I accomplish this in an smooth way?
What I tried:
const today = new Date();
const sevenDaysAgo = subDays(today, 6);
const sevenDays = eachDayOfInterval({ start: sevenDaysAgo, end: today });
sevenDays.forEach((day) => {
console.log(format(day, 'eeee', { locale: nl }));
});
This returns:
['Wednesday', 'Tuesday', 'Monday', 'Sunday', 'Saturday', 'Friday', 'Thursday']
To get the week day from the dayOffset (replace 'en-us' with your country's code if you're not American) you can do the following.
const offset_date = new Date();
offset_date.setDate(offset_date.getDate() + dayOffset);
const week_day = offset_date.toLocaleString('en-us', {weekday: 'long'});
You can use the formatRelative function from the date-fns library, it formats the dates in words from a given date.
Here is a code sandbox link that might be helpful.

is there away to replace a text if the year is greater than the currentYear.?

I wanna replace "was on " to "will be " if the year is greater than the currentYear.
let myDate = new Date();
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
const currentYear = myDate.getFullYear();
let tense = 'was on';
for(let year= 2020; year <= 2030; year++){
let d = new Date(year, 4, 27);
if(d.getDate() === 27 && d.getMonth() === 4 ){
const output = `my birthday in ${year} ${tense} ${days[d.getDay()]}`;
console.log(output)
}
}
But when I include an if statement, it's returning nothing - no error, no results.
Try this:
const days = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
const now = new Date();
const currentYear = now.getFullYear();
for(let year= 2020; year <= 2030; year++){
const d = new Date(year, 4, 27);
const tense = year > currentYear ? 'will be'
: year === currentYear ? 'is'
: 'was';
const dayOfWeek = days[d.getDay()];
if(d.getDate() === 27 && d.getMonth() === 4 ){
const output = `my birthday in ${year} ${tense} on ${dayOfWeek}`;
console.log(output)
}
}
Ideally, you should be using const wherever possible. This is also a perfect opportunity to use a ternary operator instead of an if/else-statement.
You can also make this a bit more dynamic by determine the tense first between three values— past, present, and future, and then use those values to get the actual tense values you want for different part of your desired output statement. Then, rather than using an if/else at the end, you can just use a single console.log statement and let the different cases be handled by the tenses.
My example here breaks the tenses into two groups, one for the day, and one for an added age declaration I've added. For the sake of this example, I am setting the birthday to the current date, so you can see the present tenses in action, where the output line will read My birthday in 2021 is today, on Friday, and I am 31 years old.
Here is how this would look in practice:
Iterating from birth year to 100 years later
const now = new Date(),
[currentYear, currentMonth, currentDate] = [now.getFullYear(), now.getMonth(), now.getDate()],
bday = new Date(1990, currentMonth, currentDate),
[bdayYear, bdayMonth, bdayDate] = [bday.getFullYear(), bday.getMonth(), bday.getDate()],
currentAge = currentYear - bdayYear - (
(bdayMonth < currentMonth ||
(bdayMonth === currentMonth && bdayDate <= currentDate)
) ? 0 : 1
),
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
tenses = {
date: {
past: 'was on a',
present: 'is today,',
future: 'will be on a'
},
age: {
past: 'was',
present: 'am',
future: 'will be'
}
},
_bday = new Date(bday); // cloning bday to avoid mutating the original bday date
for (let year = bdayYear; year <= bdayYear + 100; year++) {
_bday.setFullYear(year);
const [ month, date, day ] = [ _bday.getMonth(), _bday.getDate(), days[_bday.getDay()] ],
previousBday = new Date(year - 1, month, date),
age = year - bdayYear,
dateTense =
year < currentYear ||
(year === currentYear &&
(month < currentMonth ||
(month === currentMonth && date < currentDate)
)
)
? 'past'
: year === currentYear && month === currentMonth && date === currentDate
? 'present'
: 'future',
dateTenseString = tenses.date[dateTense],
ageTense = age === currentAge ? 'present' : (dateTense === 'present' ? 'past' : dateTense),
ageTenseString = tenses.age[ageTense];
document.body.innerHTML += `<span class="${ageTense}">My birthday in <b>${year}</b> ${dateTenseString} <b>${day}</b>, and I ${ageTenseString} <b>${age} years old</b>.</span>`;
}
body {
display: flex;
flex-direction: column;
margin: 0;
font-family: Arial, sans-serif;
font-size: 14px;
}
span { padding: 5px 10px; }
span:first-of-type { padding-top: 10px; }
span:last-of-type { padding-bottom: 10px; }
span.past {
background-color: #f8bbd0;
color: #880e4f;
}
span.present {
background-color: #d1c4e9;
color: #311b92;
border-top: 1px solid #311b92;
border-bottom: 1px solid #311b92;
}
span.future {
background-color: #bbdefb;
color: #0d47a1;
}
b { font-size: 120%; }
This function also intelligently compares your age with your calculated age for the current year, so if your birthday has already passed this year, it will still use the I am tense rather than the I was tense. Similarly, if your birthday is yet to come in the current year, the I am tense will be used for the previous year's age, and this year's age tense will be I will be.
You could also build this into a form, like this:
As an interactive form
const inputDob = document.getElementById('dob'),
inputYear = document.getElementById('year'),
output = document.getElementById('output'),
now = new Date(),
[currentYear, currentMonth, currentDate] = [now.getFullYear(), now.getMonth(), now.getDate()],
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
tenses = {
date: {
past: 'was on a',
present: 'is today,',
future: 'will be on a'
},
age: {
past: 'was',
present: 'am',
future: 'will be'
}
};
const calculateAge = () => {
const year = Number(inputYear.value),
bdayParts = inputDob.value.split('-').map((e,i) => Number(e) - (i === 1 ? 1 : 0)),
bday = new Date(...bdayParts),
[bdayYear, bdayMonth, bdayDate] = [bday.getFullYear(), bday.getMonth(), bday.getDate()],
currentAge = currentYear - bdayYear - (
(bdayMonth < currentMonth ||
(bdayMonth === currentMonth && bdayDate <= currentDate)
) ? 0 : 1
);
bday.setFullYear(year);
const [ month, date, day ] = [ bday.getMonth(), bday.getDate(), days[bday.getDay()] ],
previousBday = new Date(year - 1, month, date),
age = year - bdayYear,
dateTense =
year < currentYear ||
(year === currentYear &&
(month < currentMonth ||
(month === currentMonth && date < currentDate)
)
)
? 'past'
: year === currentYear && month === currentMonth && date === currentDate
? 'present'
: 'future',
dateTenseString = tenses.date[dateTense],
ageTense = age === currentAge ? 'present' : (dateTense === 'present' ? 'past' : dateTense),
ageTenseString = tenses.age[ageTense];
output.innerHTML = `<span class="${ageTense}">In <b>${year}</b>, my birthday ${dateTenseString} <b>${day}</b>, and I ${ageTenseString} <b>${age} years old</b>.</span>`;
};
calculateAge();
document.addEventListener('input', calculateAge);
body {
display: flex;
flex-direction: column;
gap: 10px;
font-family: Arial, sans-serif;
font-size: 14px;
}
span { margin-top: 0px; }
b { font-size: 120%; }
<label>My birthdate is <input id="dob" type="date" value="1990-01-01" placeholder="mm/dd/yyyy"></label>
<label>What was my birthday in the year <input id="year" type="number" value="2000"></label>
<span id="output"></span>
let myDate = new Date();
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
const currentYear = myDate.getFullYear();
let tense = 'was on';
for(let year= 2020; year <= 2030; year++){
let d = new Date(year, 4, 27);
if(d.getDate() === 27 && d.getMonth() === 4 ){
if(year < currentYear){
const output = `my birthday in ${year} ${tense} ${days[d.getDay()]}`;
console.log(output)
}else{
let tense = 'will be';
const output = `my birthday in ${year} ${tense} ${days[d.getDay()]}`;
console.log(output)
}
}
}
This works using the ternary operator in javascript.
const ripe = true;
const egg = ripe===true? "GOOD" :"BAD";
Read more here (https://www.javascripttutorial.net/javascript-ternary-operator/)
let myDate = new Date();
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
const currentYear = myDate.getFullYear();
let tense1 = 'was on';
let tense2 = "will be"
for(let year= 2020; year <= 2030; year++){
let d = new Date(year, 4, 27);
if(d.getDate() === 27 && d.getMonth() === 4 ){
// If year>currentYear then(?) tense1 else(:) tense2
const preTense = parseInt(year)>parseInt(currentYear)? tense1 : tense2;
const output = `my birthday in ${year} ${preTense} ${days[d.getDay()]}`;
console.log(output)
}
}
Here you have it :)
let myDate = new Date();
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
const currentYear = myDate.getFullYear();
let tense = 'was on';
for(let year= 2010; year <= 2030; year++){
if (parseInt(currentYear) < parseInt(year)) {tense = 'will be on';}
let d = new Date(year, 4, 27);
if(d.getDate() === 27 && d.getMonth() === 4 ){
const output = `my birthday in ${year} ${tense} ${days[d.getDay()]}`;
console.log(output)
}
}

Print weekdays and check if a date exists for this weekday

I have an array of dates
date_array = ["date1", "date2", "date3"]
I would like to print
Tuesday: Yes
Wednesday: No
Thursday: No
Friday: Yes
Saturday: No
Sunday: Yes
where Yes and No depends on whether there is a date in date_array on this weekday in the current week and the order of the weekdays should start from today's weekday.
I am using moment where the weekday number can be formatted with e, so I get the number of today's weekday with moment().format('e'). Alternatively, it could be with moment().day() where sunday=0.
I guess I could do something like
// Existing dates
var dates = [moment(), moment().add(3, 'days'), moment().add(5, 'days')]
// All weekdays to print
var weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
// Reorder
var today_weekday = moment().day()
var weekdays_reordered = weekdays.splice(today_weekday).concat(weekdays)
// Print
weekdays_reordered.map((weekday, i) => {
console.log(weekday + ': ' + (dates.some(date => date.day() === i) ? 'Yes' : 'No'));
});
<script src="https://momentjs.com/downloads/moment.min.js"></script>
But I'm not sure how exactly to make it work.
If I understood correctly, you need to print every day from current day until the end of the week, i.e. Sunday? Then, you need to set today_weekday as moment().day() - 1 (because of the indices), and then exit the loop when you get to Monday (changed it from map() to a for(), because you can't break out of map). Lastly, compare the date formated to dddd (the weekday name) to the current weekday element in the loop. Something like this:
var dates = [moment(), moment().add(4, 'days'), moment().add(5, 'days')]
// All weekdays to print
var weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
// Reorder
var today_weekday = moment().day() - 1;
var weekdays_reordered = weekdays.splice(today_weekday).concat(weekdays)
for(var i = 0; i < weekdays_reordered.length; i++) {
var weekday = weekdays_reordered[i];
if (weekday === "Monday" && i !== 0) break;
console.log(weekday + ': ' + (dates.some(date => date.format("dddd") === weekday) ? 'Yes' : 'No'));
}
<script src="https://momentjs.com/downloads/moment.js"></script>
Assuming you have an array of dates and not moment objects, you can create a date for today then check if the same date is in the array. Then step through the days of the week. Testing for date equality is a little tricky but if they are all created for say 00:00:00 then you can just check the time value.
var base = new Date();
base.setHours(0,0,0,0);
var seed = new Date(+base);
// Array of dates for today, today + 2 days, today + 4 days
var dates = [new Date(seed),
new Date(seed.setDate(seed.getDate() + 2)),
new Date(seed.setDate(seed.getDate() + 2))
];
// Test 7 days, starting from today
for (var i=7; i; --i) {
// Get weekday name in host default language
var s = base.toLocaleString(undefined, {weekday:'long'}) + ': ';
// See if there's a matching date
s += dates.find(d=>+d == +base)? 'Yes':'No';
// Add 1 to the date
base.setDate(base.getDate() + 1);
// Do something with the result
console.log(s);
}
The above requires Array.prototype.find, there's a polyfill on MDN if required. You may need to define a different comparison (predicate) function if you want to compare only date without the time.

group by weeks,days and year javascript [duplicate]

I have today = new Date(); object. I need to get first and last day of the current week. I need both variants for Sunday and Monday as a start and end day of the week. I am little bit confuse now with a code. Can your help me?
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
firstday
"Sun, 06 Mar 2011 12:25:40 GMT"
lastday
"Sat, 12 Mar 2011 12:25:40 GMT"
This works for firstday = sunday of this week and last day = saturday for this week. Extending it to run Monday to sunday is trivial.
Making it work with first and last days in different months is left as an exercise for the user
Be careful with the accepted answer, it does not set the time to 00:00:00 and 23:59:59, so you can have problems.
You can use a third party date library to deal with dates. For example:
var startOfWeek = moment().startOf('week').toDate();
var endOfWeek = moment().endOf('week').toDate();
EDIT: As of September 2020, using Moment is discouraged for new projects (blog post)
Another popular alternative is date-fns.
You can also use following lines of code to get first and last date of the week:
var curr = new Date;
var firstday = new Date(curr.setDate(curr.getDate() - curr.getDay()));
var lastday = new Date(curr.setDate(curr.getDate() - curr.getDay()+6));
Hope it will be useful..
The excellent (and immutable) date-fns library handles this most concisely:
const start = startOfWeek(date);
const end = endOfWeek(date);
Default start day of the week is Sunday (0), but it can be changed to Monday (1) like this:
const start = startOfWeek(date, {weekStartsOn: 1});
const end = endOfWeek(date, {weekStartsOn: 1});
Here's a quick way to get first and last day, for any start day.
knowing that:
1 day = 86,400,000 milliseconds.
JS dates values are in milliseconds
Recipe: figure out how many days you need to remove to get the your week's start day (multiply by 1 day's worth of milliseconds). All that is left after that is to add 6 days to get your end day.
var startDay = 1; //0=sunday, 1=monday etc.
var d = now.getDay(); //get the current day
var weekStart = new Date(now.valueOf() - (d<=0 ? 7-startDay:d-startDay)*86400000); //rewind to start day
var weekEnd = new Date(weekStart.valueOf() + 6*86400000); //add 6 days to get last day
Small change to #Chris Lang answer.
if you want Monday as the first day use this.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay()+ (this.getDay() == 0 ? -6:1) )));
}
Date.prototype.GetLastDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay() +7)));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
Thaks #Chris Lang
This works across year and month changes.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay())));
}
Date.prototype.GetLastDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay() +6)));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
You could do something like this
var today = new Date();
var startDay = 0;
var weekStart = new Date(today.getDate() - (7 + today.getDay() - startDay) % 7);
var weekEnd = new Date(today.getDate() + (7 - today.getDay() - startDay) % 7);
Where startDay is a number from 0 to 6 where 0 stands for Sunday (ie 1 = Monday, 2 = Tuesday, etc).
SetDate will sets the day of the month. Using setDate during start and end of the month,will result in wrong week
var curr = new Date("08-Jul-2014"); // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)); // 06-Jul-2014
var lastday = new Date(curr.setDate(last)); //12-Jul-2014
If u setting Date is 01-Jul-2014, it will show firstday as 29-Jun-2014 and lastday as 05-Jun-2014 instead of 05-Jul-2014
So overcome this issue i used
var curr = new Date();
day = curr.getDay();
firstday = new Date(curr.getTime() - 60*60*24* day*1000); //will return firstday (ie sunday) of the week
lastday = new Date(firstday.getTime() + 60 * 60 *24 * 6 * 1000); //adding (60*60*6*24*1000) means adding six days to the firstday which results in lastday (saturday) of the week
I recommend to use Moment.js for such cases. I had scenarios where I had to check current date time, this week, this month and this quarters date time. Above an answer helped me so I thought to share rest of the functions as well.
Simply to get current date time in specific format
case 'Today':
moment().format("DD/MM/YYYY h:mm A");
case 'This Week':
moment().endOf('isoweek').format("DD/MM/YYYY h:mm A");
Week starts from Sunday and ends on Saturday if we simply use 'week' as parameter for endOf function but to get Sunday as the end of the week we need to use 'isoweek'.
case 'This Month':
moment().endOf('month').format("DD/MM/YYYY h:mm A");
case 'This Quarter':
moment().endOf('quarter').format("DD/MM/YYYY h:mm A");
I chose this format as per my need. You can change the format according to your requirement.
//get start of week; QT
function _getStartOfWeek (date){
var iDayOfWeek = date.getDay();
var iDifference = date.getDate() - iDayOfWeek + (iDayOfWeek === 0 ? -6:1);
return new Date(date.setDate(iDifference));
},
function _getEndOfWeek(date){
return new Date(date.setDate(date.getDate() + (7 - date.getDay()) === 7 ? 0 : (7 - date.getDay()) ));
},
*current date == 30.06.2016 and monday is the first day in week.
It also works for different months and years.
Tested with qunit suite:
QUnit.module("Planung: Start of week");
QUnit.test("Should return start of week based on current date", function (assert) {
var startOfWeek = Planung._getStartOfWeek(new Date());
assert.ok( startOfWeek , "returned date: "+ startOfWeek);
});
QUnit.test("Should return start of week based on a sunday date", function (assert) {
var startOfWeek = Planung._getStartOfWeek(new Date("2016-07-03"));
assert.ok( startOfWeek , "returned date: "+ startOfWeek);
});
QUnit.test("Should return start of week based on a monday date", function (assert) {
var startOfWeek = Planung._getStartOfWeek(new Date("2016-06-27"));
assert.ok( startOfWeek , "returned date: "+ startOfWeek);
});
QUnit.module("Planung: End of week");
QUnit.test("Should return end of week based on current date", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date());
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on sunday date with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-07-03"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on monday date with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-27"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 01-06-2016 with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-01"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 21-06-2016 with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-21"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 28-12-2016 with different month and year", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-12-28"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 01-01-2016 with different month and year", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-01-01"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
var dt = new Date() //current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay-1
var wkStart = new Date(new Date(dt).setDate(dt.getDate()- lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate()+6));
This will be useful for any date scenario.
Just using pure javascript, you can use the function below to get first day and last day of a week with freely setting day for start of week.
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
function getFirstDayOfWeek(date, from) {
//Default start week from 'Sunday'. You can change it yourself.
from = from || 'Sunday';
var index = weekday.indexOf(from);
var start = index >= 0 ? index : 0;
var d = new Date(date);
var day = d.getDay();
var diff = d.getDate() - day + (start > day ? start - 7 : start);
d.setDate(diff);
return d;
};
Last day of week is just 6 days after first day of week
function getLastDayOfWeek(date, from) {
from = from || 'Sunday';
var index = weekday.indexOf(from);
var start = index >= 0 ? index : 0;
var d = new Date(date);
var day = d.getDay();
var diff = d.getDate() - day + (start > day ? start - 1 : 6 + start);
d.setDate(diff);
return d;
};
Test:
getFirstDayOfWeek('2017-10-16'); //--> Sun Oct 15 2017
getFirstDayOfWeek('2017-10-16', 'Monday'); //--> Mon Oct 16 2017
getFirstDayOfWeek('2017-10-16', 'Tuesday'); //--> Tue Oct 10 2017
The biggest issue when the given date's week is in-between two months. (Like 2022-07-01, it's the 5th day of the week.)
Using getDay function we check if the week is in-between months.
Note: getDay() function identifies week start day as sunday, so it'll return 0 for sunday.
var curr = new Date(); // get current date
var weekdaynum = curr.getDay();
if(weekdaynum == 0){ //to change sunday to the last day of the week
weekdaynum = 6;
} else{
weekdaynum = weekdaynum-1;
}
var firstweek = curr.getDate() - weekdaynum;
var lastweek = firstweek + 6; // last day is the first day + 6
if((curr.getDate()-weekdaynum) <= 0){
var firstweek_lasmonth_lastdate = new Date(currweek.getFullYear(),currweek.getMonth(), 0);
var firstweek_diff = firstweek_lasmonth_lastdate.getDate()-Math.abs(firstweek);
var firstweekday = new Date(currweek.getFullYear(),currweek.getMonth()-1,firstweek_lasmonth_lastdate.getDate()+firstweek_diff);
var lastweekday = new Date(currweek.getFullYear(),currweek.getMonth()-1,firstweek_lasmonth_lastdate.getDate()+firstweek_diff+7);
} else{
var firstweekday = new Date(curr.setDate(firstweek));
var lastweekday = new Date(curr.setDate(lastweek));
}
So this will return (given date is: 2022/07/01):
firstweekday = Mon Jun 27 2022 00:00:00
lastweekday = Sun Jul 03 2022 00:00:00
Hope this helps.
krtek's method has some wrong,I tested this
var startDay = 0;
var weekStart = new Date(today.getDate() - (7 + today.getDay() - startDay) % 7);
var weekEnd = new Date(today.getDate() + (6 - today.getDay() - startDay) % 7);
it works
Although the question is seeming as obsolete I have to point out a problem.
Question: What will happen at 1st January 2016?
I think most of the above solutions calculate start of week as 27.12.2016.
For this reason I think, the correct calculation should be like the below simply;
var d = new Date(),
dayInMs = 1000 * 60 * 60 * 24,
weekInMs = dayInMs * 7,
startOfToday = new Date(d.getFullYear(), d.getMonth(), d.getDate()).valueOf(),
todayElapsedTime = d.valueOf() - startOfToday,
dayDiff = d.getDay() * dayInMs,
dateDiff = dayDiff + todayElapsedTime,
// finally
startOfWeek = d.valueOf() - dateDiff,
endOfWeek = startOfWeek + weekInMs - 1;
JavaScript
function getWeekDays(curr, firstDay = 1 /* 0=Sun, 1=Mon, ... */) {
var cd = curr.getDate() - curr.getDay();
var from = new Date(curr.setDate(cd + firstDay));
var to = new Date(curr.setDate(cd + 6 + firstDay));
return {
from,
to,
};
};
TypeScript
export enum WEEK_DAYS {
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
}
export const getWeekDays = (
curr: Date,
firstDay: WEEK_DAYS = WEEK_DAYS.Monday
): { from: Date; to: Date } => {
const cd = curr.getDate() - curr.getDay();
const from = new Date(curr.setDate(cd + firstDay));
const to = new Date(curr.setDate(cd + 6 + firstDay));
return {
from,
to,
};
};
function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
return new Date(d.setDate(diff));
}
console.log( getMonday(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())) ) // Mon Nov 08 2010
Pure vanilla JS. no third party libraries.
const now = new Date()
const startOfWeek = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay())
const endOfWeek = new Date(now.getFullYear(), now.getMonth(), startOfWeek.getDate() + 7)
^ this returns Sunday 00am to Sunday 00am. Adjust the "7" to get what you want.
var currentDate = new Date();
var firstday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay())).toUTCString();
var lastday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 6)).toUTCString();
console.log("firstday", firstday);
console.log("lastday", lastday);
Works with different months and years.
let wDate = new Date();
let dDay = wDate.getDay() > 0 ? wDate.getDay() : 7;
let first = wDate.getDate() - dDay + 1;
let firstDayWeek = new Date(wDate.setDate(first));
let lastDayWeek = new Date(wDate.setDate(firstDayWeek.getDate()+6));
console.log(firstDayWeek.toLocaleDateString());
console.log(lastDayWeek.toLocaleDateString());
Nice suggestion but you got a small problem in lastday.
You should change it to:
lastday = new Date(firstday.getTime() + 60 * 60 *24 * 6 * 1000);
The moment approach worked for me for all the cases ( although i have not test the boundaries like year end , leap years ). Only Correction in the above code is the parameter is "isoWeek" , if you want to start the week from Monday.
let startOfWeek = moment().startOf("isoWeek").toDate();
let endOfWeek = moment().endOf("isoWeek").toDate();
We have added jquery code that shows the current week of days from monday to sunday.
var d = new Date();
var week = [];
var _days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var _months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
for (let i = 1; i <= 7; i++) {
let first = d.getDate() - d.getDay() + i;
let dt = new Date(d.setDate(first));
var _day = _days[dt.getDay()];
var _month = _months[dt.getMonth()];
var _date = dt.getDate();
if(_date < 10 ){
_date = '0' +_date;
}
var _year = dt.getFullYear();
var fulldate = _day+' '+_month+' '+_date+' '+_year+' ';
week.push(fulldate);
}
console.log(week);
An old question with lots of answers, so another one won't be an issue. Some general functions to get the start and end of all sorts of time units.
For startOf and endOf week, the start day of the week defaults to Sunday (0) but any day can be passed (Monday - 1, Tuesday - 2, etc.). Only uses Gregorian calendar though.
The functions don't mutate the source date, so to see if a date is in the same week as some other date (week starting on Monday):
if (d >= startOf('week', d1, 1) && d <= endOf('week', d1, 1)) {
// d is in same week as d1
}
or in the current week starting on Sunday:
if (d >= startOf('week') && d <= endOf('week')) {
// d is in the current week
}
// Returns a new Date object set to start of given unit
// For start of week, accepts any day as start
function startOf(unit, date = new Date(), weekStartDay = 0) {
// Copy original so don't modify it
let d = new Date(date);
let e = new Date(d);
e.setHours(23,59,59,999);
// Define methods
let start = {
second: d => d.setMilliseconds(0),
minute: d => d.setSeconds(0,0),
hour : d => d.setMinutes(0,0,0),
day : d => d.setHours(0,0,0,0),
week : d => {
start.day(d);
d.setDate(d.getDate() - d.getDay() + weekStartDay);
if (d > e) d.setDate(d.getDate() - 7);
},
month : d => {
start.day(d);
d.setDate(1);
},
year : d => {
start.day(d);
d.setMonth(0, 1);
},
decade: d => {
start.year(d);
let year = d.getFullYear();
d.setFullYear(year - year % 10);
},
century: d => {
start.year(d);
let year = d.getFullYear();
d.setFullYear(year - year % 100);
},
millenium: d => {
start.year(d);
let year = d.getFullYear();
d.setFullYear(year - year % 1000);
}
}
start[unit](d);
return d;
}
// Returns a new Date object set to end of given unit
// For end of week, accepts any day as start day
// Requires startOf
function endOf(unit, date = new Date(), weekStartDay = 0) {
// Copy original so don't modify it
let d = new Date(date);
let e = new Date(date);
e.setHours(23,59,59,999);
// Define methods
let end = {
second: d => d.setMilliseconds(999),
minute: d => d.setSeconds(59,999),
hour : d => d.setMinutes(59,59,999),
day : d => d.setHours(23,59,59,999),
week : w => {
w = startOf('week', w, weekStartDay);
w.setDate(w.getDate() + 6);
end.day(w);
d = w;
},
month : d => {
d.setMonth(d.getMonth() + 1, 0);
end.day(d);
},
year : d => {
d.setMonth(11, 31);
end.day(d);
},
decade: d => {
end.year(d);
let y = d.getFullYear();
d.setFullYear(y - y % 10 + 9);
},
century: d => {
end.year(d);
let y = d.getFullYear();
d.setFullYear(y - y % 100 + 99);
},
millenium: d => {
end.year(d);
let y = d.getFullYear();
d.setFullYear(y - y % 1000 + 999);
}
}
end[unit](d);
return d;
}
// Examples
let d = new Date();
['second','minute','hour','day','week','month','year',
'decade','century','millenium'].forEach(unit => {
console.log(('Start of ' + unit).padEnd(18) + ': ' +
startOf(unit, d).toString());
console.log(('End of ' + unit).padEnd(18) + ': ' +
endOf(unit, d).toString());
});
var currentDate = new Date();
var firstday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay())).toUTCString();
var lastday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 7)).toUTCString();
console.log(firstday, lastday)
I'm using the following code in but because of .toUTCString() i'm receiving the following error as show in image.
if i remove .toUTCString(). output which i receive is not as expected
Small change to #SHIVA's answer which is a changed #Chris Lang answer.
For monday first usage with fix when today is sunday.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay()+ (this.getDay() == 0 ? -6:1) )));
}
Date.prototype.GetLastDayOfWeek = function() {
return new Date(this.setDate(this.getDate() - (this.getDay() == 0 ? 7 : this.getDay()) + 7));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
You can try the below one too
let weekBgnDt = new Date();
let weekEndDt = new Date();
let wBeginDateLng, wEndDateLng, diffDays,dateCols=[];
if (weekBgnDt.getDay() > 0) {
diffDays = 0 - weekBgnDt.getDay();
weekBgnDt.setDate(weekBgnDt.getDate() + diffDays)
}
weekEndDt = weekEndDt.setDate(weekBgnDt.getDate() + 6)
wBeginDate = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: '2-digit' }).format(weekBgnDt);
wEndDate = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric', month:
'2-digit' }).format(weekEndDt);
wBeginDateLng = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: 'long' }).format(weekBgnDt);
wEndDateLng = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: 'long' }).format(weekEndDt);
console.log(wBeginDate, "-", wBeginDateLng)
console.log(wEndDate, "-", wEndDateLng)
for(let i=weekBgnDt;i<=weekEndDt;){
dateCols.push(new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: '2-digit' }).format(i));
i=weekBgnDt.setDate(weekBgnDt.getDate()+1)
}
console.log({wBeginDate,wBeginDateLng,wEndDate,wEndDateLng,dateCols})
The result will be printed as
{ wBeginDate: "16/05/2021", wBeginDateLng: "16 May 2021", wEndDate: "22/05/2021", wEndDateLng: "22 May 2021", dateCols: Array ["16/05/2021", "17/05/2021", "18/05/2021", "19/05/2021", "20/05/2021", "21/05/2021", "22/05/2021"] }
The right way to get the first and last date of the current week with appropriate month & year is as below
const curr = new Date();
const first = curr.getDate() - curr.getDay() + 1; // Start from Monday
const firstDate = new Date(curr.setDate(first));
const lastDate = new Date(curr.setDate(firstDate.getDate() + 6));
console.log(firstDate.toLocaleDateString(), lastDate.toLocaleDateString());
You can use this function, it works with first and last day of the week in different months or years
const getFirstAndLastDayOfTheWeek = () => {
// The starting time is the same current
let a = new Date();
let b = new Date();
const weekDay = a.getDay();
if (weekDay === 0) {
a.setDate(a.getDate() - 6);
} else if (weekDay === 1) {
b.setDate(b.getDate() + 7 - b.getDay());
} else if (weekDay >= 1) {
a.setDate(a.getDate() - a.getDay() + 1);
b.setDate(b.getDate() + 7 - b.getDay());
}
return { firstWeekDate: a, lastWeekDate: b };
}
console.log(getFirstAndLastDayOfTheWeek());

Create an Array of names of last 7 days starting from today - javascript

I'm trying to figure out, how to create a javascript array of names of ie. last 7 days starting from today.
I know getDay() will return a number of the day, which I can then use as an index to access an element of an array containing days of the week.
This will give me the name of today, but I need to go back chronologically to create an array of last few days I couldn't find anything similar to this problem on web.
Any elegant solution for this? jQuery perhaps?
const days = ['monday', 'tuesday', 'wednesday', 'thursday',
'friday', 'saterday', 'sunday'];
var goBackDays = 7;
var today = new Date();
var daysSorted = [];
for(var i = 0; i < goBackDays; i++) {
var newDate = new Date(today.setDate(today.getDate() - 1));
daysSorted.push(days[newDate.getDay()]);
}
alert(daysSorted);
function myFunction(day) {
var weekday =["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
return weekday[day];
}
var currentDate = new Date().getDay();
var week=[0,1,2,3,4,5,6];
var a=week.splice(currentDate);
var loopWeek=a.concat(week);
var freshWeek=[];
for(var i=0;i<loopWeek.length;i++){
freshWeek.push(myFunction(loopWeek[i]))
}
console.log(freshWeek);
Maybe not the most elegant way:
var numdays = 7; // Change it to the number of days you need
var d = new Date();
var n = d.getDay();
var weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
var myArray = new Array(numdays);
for(var i=0;i<numdays;i++){
myArray[i]=weekday[(n-i+numdays)%7];
}
console.log(myArray); // Result: ["Thursday", "Wednesday", "Tuesday", "Monday", "Sunday", "Saturday", "Friday"]

Categories