Get same weekend last year using moment js - javascript

I'm trying to get the same day of the year last week so i can compare some analytics.
Using moment i can easily do this
var today = new Date();
//Sunday 4 September 2016 - Week 36
var lastYear = new moment(today).subtract(12, 'months').toDate();
//Friday 4 September 2015 - Week 37
What i am trying to do is get the same 'Sunday' last year, so Sunday week 36 2015
Any idea how to do this?

Here's what I came up with:
let today = moment();
let lastYear = moment().subtract(1, 'year')
.isoWeek(today.isoWeek())
.isoWeekday(today.isoWeekday());
It takes today as start point, subtracts a year, and sets the week and weekday to the ones from today.
So today (Tue Sept 13 2016, aka 2016-W37-2) last year was Tue Sept 8 2015 (aka 2015-W37-2).

// Typescript
var lastYear: moment.Moment = moment().subtract(1, "year");

As of version 2.0.0 moment.js supports .endOf('week') method, try
var lastYear = moment().subtract(1, 'years').endOf('week');
This will give you a 23:59:59 time, so you might also want to call .startOf('day') to get 00:00:00 of the same day:
var lastYear = moment().subtract(1, 'years').endOf('week').startOf('day');
Depending on your locale, your week may be from Monday to Sunday or from Sunday to Saturday, so I guess you'll have to account for that, too.
Edit
I've looked up documentation, and it appears you can set day of week this way, too:
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)
So in your case it will be
var lastYear = moment().day(-52 * 7); // a Sunday 52 weeks ago
Or the two methods combined
var lastYear = moment().subtract(1, 'years').day(7); // a Sunday after the date that was 1 year ago

Related

Moment.js Why Dates with provided year + week gives the previous week?

Hello I am using moment to create a week Calendar:
Current Week #26 -> From Sunday June 27th to Saturday July 3th
const year = 2021;
const week = 26;
moment().year(year).week(week). // prints Sun Jun 20 2021 10:36:14 GMT-0500
Why I obtain the previous week ?
Short Answer I can plus one, but I do not understand why :(
BAD thing:
const startDay = moment(
moment().year(year).week(week + 1)
)
.startOf('week');
const endDay = moment(
moment().year(year).week(week + 1)
)
.endOf('week');
Extra info:
moment().year(2021).week(1) // Sun Dec 27 2020 10:51:41 GMT-0600
instead of January 3th to January 9th
Try using moment.utc which should convert all the dates according to the Universal time

How to convert date values to number of days

I am trying to add days to a date. I am taking input from the user where I have separate input boxes for the each field like no. of years, no of months and no of days like this.
as you can see in the 2nd input field row I am accepting no of years, days, months, etc.
and in First row I am getting a proper date like : 2020 10 05 00 00 00
and then passing them to date constructor to gate date.
ex. Date firstdate = new Date(2020, 10, 05, 00, 00,00);
and I am adding days to the above date using the following function
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
I am adding days to the previous date by calling a function like this.
var newdate = firstdate.addDays(totaldays);
Now the problem is while I am calculating days it is not including leap years and months with their specified date. because I am calculating days like this way:
totaldays = (years * 365) + (months * 30) + days;
What is the way so I can add days perfectly? for example, if the user entered date like
2020 12 10 00 00 00
and add the number of days and years like this
1 year 3 months 0 days 00 00 00
so it should ideally calculate 3 months that is January, February, march, as the user has entered the date of December so next three months date should be added.
SO How do I get the perfect number of days?
Sorry, this question can feel so long or improper. but I am working on this from a week.
Note: I cannot use any external link, API, Library as this is a school project.
Any help will be great. also sorry for my English. I'm not a native speaker.
Let the Date object do it for you, by using getFullyear/setFullYear, getMonth/setMonth, and getDate/setDate. They handle rollover and leap years:
const yearsToAdd = 1;
const monthsToAdd = 3;
const daysToAdd = 0;
const date = new Date(2020, 12 - 1, 10);
console.log(date.toString());
date.setFullYear(date.getFullYear() + yearsToAdd);
date.setMonth(date.getMonth() + monthsToAdd);
date.setDate(date.getDate() + daysToAdd);
console.log(date.toString());
Just as an example of handling leap years, here's that code adding two days to Feb 28th 2020 (which was a leap year, so there was a Feb 29th):
const yearsToAdd = 0;
const monthsToAdd = 0;
const daysToAdd = 2;
const date = new Date(2020, 2 - 1, 28);
console.log(date.toString());
date.setFullYear(date.getFullYear() + yearsToAdd);
date.setMonth(date.getMonth() + monthsToAdd);
date.setDate(date.getDate() + daysToAdd);
console.log(date.toString());
Notice how it goes to March 1st, not March 2nd, as it does in 2019:
const yearsToAdd = 0;
const monthsToAdd = 0;
const daysToAdd = 2;
const date = new Date(2019, 2 - 1, 28);
console.log(date.toString());
date.setFullYear(date.getFullYear() + yearsToAdd);
date.setMonth(date.getMonth() + monthsToAdd);
date.setDate(date.getDate() + daysToAdd);
console.log(date.toString());
This is a duplicate of other questions:
Add A Year To Today's Date
JavaScript function to add X months to a date
Add days to JavaScript Date
To summarise some of the issues:
Days are not always 24 hours long where daylight saving occurs, so you must determine whether "adding 1 day" means adding 1 calendar day or adding 24 hours
Months are 28 to 31 days long, so adding 1 month adds a different number of days depending on the month you're adding to
Years are 365 or 366 days long. In a leap year, adding 1 year to 29 Feb adds 366 days and ends on 2 Mar. The following day, adding 1 year to 1 Mar ends on 1 Mar
There are other quirks with leap years and month lengths not mentioned above, such as 31 Aug + 1 month gives 1 Oct, because adding a month in August adds 31 days.
So you can either add business rules to deal with the quirks, or just let them happen.
In reagard to adding years, months and days, that can be done in one call to setFullYear:
date.setFullYear(date.getFullYear() + yearsToAdd,
date.getMonth() + monthsToAdd,
date.getDate() + daysToAdd);
Adding them all at once can have a different result to adding them one at a time.
Given that you are getting values for the year, month, day, etc. then the values to add, you can simply add corresponding values (ensuring you convert strings to numbers before adding) and call the Date constructor once:
let date = new Date(startYear + yearsToAdd,
startMonth - 1 + monthsToAdd, // Assuming user enters calendar month
startDay + daysToAdd,
startHour + hoursToAdd,
startMinute + minutesToAdd,
startSecond + secondsToAdd);

Moment.js, Get next [weekday]

Trying to get second coming Thursday (e.g.) using moment.js. Not this Thursday. The next one. The date in 2 Thursdays.
I have tried
moment().add(1, 'week').day(4)
which just fetches Thursday of the next week (only works if current weekday is before Thursday)
Any ideas?
"which just fetches Thursday of the next week (only works if current weekday is before Thursday)"
It's happening because .add(1, 'week') just adds 7 days and gets you the next week date and you are fetching 4th day of that week.
Below code will work for your case perfectly.
if(moment().weekday() < 4)
moment().add(1, 'week').day(4);
else
moment().add(2, 'week').day(4);
Not sure about using moment.js, but in plain js next Thursday is given by:
currentDate + (11 - d.getDay() % 7)
For the following Thursday, just add 7 days. Presumably if the current day is Thursday, want the Thursday in two weeks so:
var d = new Date();
console.log(d.toString());
// Shift to next Thursday
d.setDate(d.getDate() + ((11 - d.getDay()) % 7 || 7) + 7)
console.log(d.toString())
Or encapsulated in a function with some tests:
function nextThursdayWeek(d) {
d = d || new Date();
d.setDate(d.getDate() + ((11 - d.getDay()) % 7 || 7) + 7);
return d;
}
// Test data
[new Date(2017,2,6), // Mon 6 Mar 2017
new Date(2017,2,7), // Tue 7 Mar 2017
new Date(2017,2,8), // Wed 8 Mar 2017
new Date(2017,2,9), // Thu 9 Mar 2017
new Date(2017,2,10), // Fri 10 Mar 2017
new Date(2017,2,11), // Sat 11 Mar 2017
new Date(2017,2,12), // Sun 12 Mar 2017
new Date() // Today
].forEach(function (date) {
console.log(date.toString() + ' -> ' + nextThursdayWeek(date).toString());
});

Are there any JavaScript methods that can replicate the Oracle's ADD_MONTH() functionality

1) Oracle's example of ADD_MONTHS(date, 1):
SELECT ADD_MONTHS('30-Nov-15', 3) FROM dual;
February, 29 2016 00:00:00
2) JavaScript:
var date= new Date("Mon Nov 30 2015 00:00:00");
date.setMonth(date.getMonth() + 3);
Tue Mar 01 2016 00:00:00
Are there any JavaScript methods that can replicate the Oracle's ADD_MONTH() functionality ?
If you want to implement the same logik as in Oracle function - i.e. for "shorter" month you do not overflow in the next month, I guess you will need to do it yourself:
Pseudocode:
myDay = date.getDate(); // save the date
date.setMonth(date.getMonth() + 3); // add months
myNewDay = date.getDate();
while (myDay != myNewDay & myNewDay <= 3) {
myNewDay = myNewDay -1 // go back one day
date.setDate(myNewDay); // restore the
}
So if you end with the same day of the month after adding months you are ready.
If you get a different day of month, it will be 1,2 or 3 (the difference in month length);
go back day by day until you reach the end of the month.
This is my knowledge of the Oracle algorithm. HTH.
date.getMonth()
returns the previous months date instead of this months date. So to add to the correct date just do
date.setMonth(date.getMonth() + 2);

Get start and end day of week considering year starting in the middle of week [duplicate]

This question already has answers here:
How to get first and last day of the current week in JavaScript
(32 answers)
Closed 7 years ago.
I was using a function to return me the start and end day of a given week number from the year. Here is the function:
function getWeekRange(week){
var d = new Date("Jan 01, " + $scope.today.getFullYear() + " 01:00:00");
var w = d.getTime() + 604800000 * (week);
var d1 = new Date(w);
var d2 = new Date(w + 518400000);
return {
startDate: d1,
endDate: d2,
};
}
I set the year dynamically, and let's see an example where the year is 2015. Considering the week number starting by 0, if I use getWeekRange(0) I will receive the following result:
{
startDate: Thu Jan 01 2015 01:00:00 GMT-0200 (BRST),
endDate: Wed Jan 07 2015 01:00:00 GMT-0200 (BRST)
}
The problem is that this code does not consider the year of 2015 starting on a Thursday. The correct result for getWeekRange(0) should be:
{
startDate: Thu Jan 01 2015 01:00:00 GMT-0200 (BRST),
endDate: Sat Jan 03 2015 01:00:00 GMT-0200 (BRST)
}
and the result for getWeekRange(1) should be:
{
startDate: Sun Jan 04 2015 01:00:00 GMT-0200 (BRST),
endDate: Sat Jan 10 2015 01:00:00 GMT-0200 (BRST)
}
Does anyone have a clue?
-- EDIT --
My question is different from this one, because I don't have a given day of the year, I have only a week number of the year (from 0 to 51), and my case considers that the first week of the year is only a part of a full week, as mentioned by likeitlikeit.
I could find a simple solution for my question, since only the first week of my year could cause me problems. Here is the code:
function getWeekRange(week){
var d = new Date("Jan 01, " + $scope.today.getFullYear() + " 01:00:00");
var firstWeekDays = 7 - d.getDay();
var d1, d2;
if(week > 0) {
var w = d.getTime() + 604800000 * (week-1) + 24*60*60*1000 * firstWeekDays;
d1 = new Date(w);
d2 = new Date(w + 518400000);
} else {
d1 = d;
d2 = new Date(d1.getTime() + 24*60*60*1000 * (6 - d1.getDay()));
}
return {
startDate: d1,
endDate: d2,
};
}
There are 2 main diferences from the initial code.
For the week of the year I simply get the initial day of the year, and then based on the day of the week it starts I can find the end day of the week
For the other weeks, I sum 7*week-1 days to initial day (this sum does not consider the number of days of the first week), and also add firstWeekDays which is the number of days of first week (because it is not always 7 as the other weeks).
If anyone has a better solution, I will be glad to listen.
This answer shows how to get the first day of a week using getDate to calculate the offset from the current day.
Using this method, you can use getDate to determine which day of the week the first day of the year falls on. You can then subtract the last day of the week from this value to know how many days to add to your d2 in order to compute the date for Saturday by adjusting your date from the first day of the year + the offset in days till the end of the week for Jan 1.

Categories

Resources