且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Moment.js查找当前周的特定日期

更新时间:2023-01-31 14:49:32

本周的星期天

  moment()一周')

本周星期一

  moment()。startOf('isoweek')

星期六

  moment()。endOf('week')

当天到星期日之间的差异

  moment()。diff (moment()。startOf('week'),'days')

本周的wedesday



  moment()。startOf('week')。add('days',3)


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.

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)