Javascript: getting wrong dates of current weeks - javascript

I want to get all the seven dates (Monday to Sunday) from the current week. The below code is working well.
let curr = new Date(); // today's date is: 15th April 2020
let week = []
for (let i = 1; i <= 7; i++) {
let first = curr.getDate() - curr.getDay() + i;
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10)
week.push(day);
}
console.log(week); // output: ["2020-04-13", "2020-04-14", "2020-04-15", "2020-04-16", "2020-04-17", "2020-04-18", "2020-04-19"]
However, assume the current date is 19th April 2020. Then the code is returning the wrong dates.
let curr = new Date('2020-04-19'); // today's date is: 19th April 2020
let week = []
for (let i = 1; i <= 7; i++) {
let first = curr.getDate() - curr.getDay() + i;
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10)
week.push(day);
}
console.log(week); // output: ["2020-04-20", "2020-04-21", "2020-04-22", "2020-04-23", "2020-04-24", "2020-04-25", "2020-04-26"]
It should return the output like
["2020-04-13", "2020-04-14", "2020-04-15", "2020-04-16", "2020-04-17", "2020-04-18", "2020-04-19"]

It looks like if curr falls on a Sunday, you want to jump back an entire week, so I would change this line:
let first = curr.getDate() - curr.getDay() + i;
to:
let first = curr.getDate() - ( curr.getDay() ? curr.getDay() : 7 ) + i;

Since getDay() returns 0 for Sunday, but your code requires 7 to find the preceding Monday, you just need to allow for that and adjust when required:
let curr = new Date('2020-04-19'); // today's date is: 19th April 2020
let week = []
for (let i = 1; i <= 7; i++) {
let dow = curr.getDay();
if (!dow) dow = 7;
let first = curr.getDate() - dow + i;
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10)
week.push(day);
}
console.log(week);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay
For Sundays, getDay() will return 0, not 7.

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 get current week date in javascript?

I have a problem getting the current week date in javascript. I wrote the following code to get the current week's date, It was working well but it seems it sometimes returns the next week's date. I could not understand where is the problem.
any help would be appreciated.
This is my code:
let curr = new Date();
let week = [];
for (let i = 1; i <= 7; i++) {
let first = curr.getDate() - curr.getDay() + i;
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10);
week.push(day);
};
console.log(week)
The output:
['2022-06-13', '2022-06-14', '2022-06-15', '2022-06-16', '2022-06-17', '2022-06-18', '2022-06-19']
but today's date is 6/12/2022, but the above date started from 13/06/2022
Source:
here
When you do +i you are adding numbers 1 to 7 to your first variable. Now since the week starts from Sunday=0, you do not need to add an offset.
Just iterate loop from 0 to 6:
let curr = new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000));
let week = [];
for (let i = 0; i < 7; i++) {
let first = curr.getDate() - curr.getDay() + i;
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10);
week.push(day);
};
console.log(week)
[Edit] : If you want to get from 7 days ago, you can change how you initialize your curr variable.
From this :
let curr = new Date();
to this:
let curr = new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000));
I use the getTime() method to get the epoch of today's date and subtract exactly the milliseconds passed in 7 days (or 1 week).
If I understand your question correctly, you must take into consideration when current day is sunday to get current week first day (monday).
let curr = new Date();
let week = [];
for (let i = 1; i <= 7; i++) {
let first = curr.getDate() - curr.getDay() + i;
if (curr.getDay() === 0){
first = curr.getDate() - 6;
}
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10);
week.push(day);
};
console.log(week)
Start the for loop from 0
Like so
let curr = new Date();
let week = [];
for (let i = 0; i < 7; i++) {
let first = curr.getDate() - curr.getDay() + I;
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10);
week.push(day);
};
console.log(week)
Remember, if you start from 1 and add 1 to the current date it will return tomorrow, and if you add 0 to today it retustns this date.
You can use moment.js library
let week = [];
let firstDayOfWeek = moment().startOf('week');
for (let i = 0; i < 7; i++) {
week.push(moment(firstDayOfWeek).add(i, 'd'));
};
console.log(week)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

Get the day number from moment object javascript

I have a moment data object, what i want to do is get the date number, like if 2018-12-31 is given, it should return 365.
What I've currently done is this, but I feel like this is a more brute force approach since I have to run this function over and over again. Is there a more elegant way of doing this through the momentjs library?
var day = 25;
var mon = 12;
var year = 2018;
var sum = 0;
var days = 0;
var month_day = [31,28,31,30,31,30,31,31,30,31,30,31];
for ( var i = 0; i < mon; i++){
sum += month_day[i];
}
days = sum - (month_day[mon-1] - day);
console.log(days)
You can use the dayOfYear() function:
const day = 25;
const month = 12 - 1; // months are 0-based when using the object constructor
const year = 2018;
const date = moment({day, month, year});
console.log(date.dayOfYear()); // 359
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
You can do it without momentjs
let year = 2018;
let month = 12 - 1;
let day = 25;
let dayOfYear = (Date.UTC(year, month, day) - Date.UTC(year, 0, 1)) / 86400000 + 1;
console.log(dayOfYear);
The moment documentation is helpful: https://momentjs.com/docs/#/get-set/day-of-year/
var day = 25;
var mon = 12;
var year = 2018;
console.log(moment().year(year).month(mon).date(day).dayOfYear());

Why its not giving me the correct total month?

Why it's not giving me the correct total month? (with compared to current mm-yyyy)
function get_total_month(mm,yyyy) {
// custom inputs
var start_date = new Date(yyyy, mm, 01);
// current date
var today_date = new Date();
var today_year = today_date.getFullYear();
var today_month = today_date.getMonth();
var today_day = today_date.getDate();
var end_date = new Date(new Date(today_year, today_month, today_day));
// compare the given date with current date to find the total months
var total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth());
return total_months;
}
alert(
get_total_month(01, 2014)
);
Giving me: 20 instead of 22
That's because the Date.prototype.getMonth method returns a 0-11 number. So:
January = 0
February = 1
...
December = 11
I think this is what you are looking for, it is another version of your code. But I think is shorter and easier to understand. What do you think?
(I added the +2 to adjust the result to what you are expecting the function to return)
function monthDifference(startDate) {
var months;
var currentDate = new Date();
months = (currentDate.getFullYear() - startDate.getFullYear()) * 12;
months -= startDate.getMonth() + 1;
months += currentDate.getMonth();
return months <= 0 ? 0 : (months + 2);
}
alert(monthDifference(new Date(2014,0)) );
alert(monthDifference(new Date(2013,11)) );

How to loop through weekdays in a month?

monthDays = 31;
dayOfMonth = 9;
weekOfMonth = 2;
startDay = weekStartingDate (weekOfMonth); // function return 8
// startDay could be 8, 15, 22 or 28
for (var day = startDay; day < (startDay+7) ; day++)
{
//stuff
}
The problem is, when startDay is 29+, that (startDay+7) exceds monthDays
I want to loop through days considering weekdays ranges.
You should define the limit value to your for loop
for (var day = startDay; day < ((startDay+7) > monthDays ? monthDays : (startDay+7)) ; day++)
{
//stuff
}
monthDays = 31;
dayOfMonth = 9;
weekOfMonth = 2;
startDay = weekStartingDate (weekOfMonth); // function return 8
for (var day = startDay; day < (startDay+7) ; day++)
{
//stuff
if(x >=31 ){
break;
}
}
Why not use a tertiary?
monthDays = 31;
dayOfMonth = 9;
weekOfMonth = 2;
startDay = weekStartingDate (weekOfMonth); // function return 8
var maxDay = (startDay+7) > monthDays ? monthDays : (startDay+7)
// startDay could be 8, 15, 22 or 28
for (var day = startDay; day <= maxDay ; day++)
{
//stuff
}
Instead of (startDay+7) use (startDay+7)%monthDays
Not quite sure what you are trying to do, but it seem you are trying to get the dates for a week that are in the same month.
The functions below do that. getWeekStartDate returns a Date for the start of the week for a given date, optionally starting on Monday or Sunday. getNext7DatesInMonth gets up to 7 days from the given a date in the same month.
The result is an array of numbers for the required dates.
/*
** #param {Date} date
** #param {boolean} weekStartsOnMon - true if week starts on Monday
** #returns {Date} - new date object for first day of week
*/
function getWeekStartDate(date, weekStartsOnMon) {
var d = new Date(+date);
var dayNum = d.getDay();
// If start of week is Monday
if (weekStartsOnMon) {
d.setDate(d.getDate() - (dayNum? dayNum : 7) +1)
;
// If start of week is Sunday
} else {
d.setDate(d.getDate() - d.getDay());
}
return d;
}
/*
** For the given date, get the dates in the week for the same month.
**
** #param {Date} date
** #param {boolean} weekStartsOnMon - true if week starts on Monday
** #returns {Array} - String dates for rest of week in same month as date
*/
function getNext7DatesInMonth(date){
var start = new Date(+date);
var monthNum = start.getMonth();
var weekDates = [];
var i = 7;
while (monthNum == start.getMonth() && i--) {
weekDates.push(start.getDate());
start.setDate(start.getDate() + 1);
}
return weekDates;
}
// Start week on Sunday
var d = new Date(2015,4,31)
console.log(d + ': ' + getNext7DatesInMonth(getWeekStartDate(d, false))); // 31
// Start week on Monday
var d = new Date(2015,4,31)
console.log(d + ': ' + getNext7DatesInMonth(getWeekStartDate(d, true))); // 25,26,27,28,29,30,31
You could do a similar function without Date objects based on getting the number of days in the month, but Date objects are convenient.

Categories