Question

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 fiddle.

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.

Était-ce utile?

La solution

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)

Autres conseils

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.

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);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top