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?
let today = moment(); let lastYear = moment(). subtract(1, 'year') .
However, Moment. js has too many drawbacks compared to modern date and time libraries. Its API is not immutable, it is large and it doesn't support tree shaking. Even the Moment team discourages to use their library in new projects.
Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.
Just import moment in your file and call moment(). subtract(1, "month"). format('MMMM') and it will return previous month.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With