Using Moment.js to find a specific day of the current week's date
Solution 1
this week's sunday
moment().startOf('week')
this week's monday
moment().startOf('isoweek')
this week's saturday
moment().endOf('week')
difference between the current day to sunday
moment().diff(moment().startOf('week'),'days')
this week's wedesday
moment().startOf('week').add('days', 3)
Solution 2
Maybe a little late to the party, but here's the proper way to do this, as in the documentation.
moment().day(1); // Monday in the current week
Also if in your locale it happens that the week starts with Monday and you wish to get a locally aware result, you can use moment().weekday(0)
. Here's the documentation for the moment().weekday(dayNumber)
method.
Solution 3
It's not longer possible to use just a string (e. g. 'isoweek'), we need to use it like this:
import * as moment from 'moment';
import { unitOfTime } from 'moment';
moment().startOf('isoweek' as unitOfTime.StartOf);
Admin
Updated on May 17, 2020Comments
-
Admin almost 4 years
Finding the date of a specific day of the current week with Moment.js
There are lots of ways to manipulate dates in javascript. I've been looking for the simplest, easiest way to do so without long, ugly code, so someone showed me Moment.js.
I want to use the current date to discover the date of a specific day of the current week with this library. My attempt so far involves taking the difference between the current day number(days 0-6) and checking how many days are between it and monday(day 1), which is not right at all.
Here's my code:
var now = moment(); var day = now.day(); var week = [['sunday',0],['monday',1],['tuesday',2],['wednesday',3],['thursday',4],['friday',5],['saturday',6]]; var monday = moment().day(-(week[1][1] - day));//today minus the difference between monday and today $("#console").text(monday); //I need to know the date of the current week's monday //I need to know the date of the current week's friday
How can I do this? My method may be a terrible way to get this done, or it might be somewhat close. I do, however want the solution to be neat, small, dynamic, and simple, as all code should be.
I'd prefer not to use native JS date functionality which produces ugly, messy code in every situation that I've seen.
-
LaurelT over 7 yearsNote that
moment().add('days', 3)
has been depricated in the latest version of moment. It should now bemoment().add(3, 'days')
-
Muhammad Shaharyar about 7 yearscan we find startOf of a particular year ?
-
danish ali almost 3 yearsfor me.
moment(date).endOf('week')
worked for sunday -
Jaybeecave almost 3 yearsI think this is if you are using typescript, not because its no longer possible.