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

29 javascript jquery date momentjs

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


有很多方法可以在javascript中操作日期.我一直在寻找最简单,最简单的方法,没有冗长,丑陋的代码,所以有人向我展示了Moment.js.

我想使用当前日期通过此库发现当前一周特定日期的日期.到目前为止,我的尝试涉及取当前日数(第0-6天)和检查它与星期一(第1天)之间的天数之间的差异,这是不正确的.

这是我的小提琴.

这是我的代码:

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
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?我的方法可能是完成这项工作的可怕方法,或者可能有些接近.我确实希望解决方案整洁,小巧,动态,简单,因为所有代码都应如此.

我宁愿不使用本机JS日期功能,在我看到的每种情况下都会产生丑陋,凌乱的代码.

way*_*yne 66

本周的周日

moment().startOf('week')
Run Code Online (Sandbox Code Playgroud)

本周的星期一

moment().startOf('isoweek')
Run Code Online (Sandbox Code Playgroud)

本周的周六

moment().endOf('week')
Run Code Online (Sandbox Code Playgroud)

当天到周日之间的差异

moment().diff(moment().startOf('week'),'days')
Run Code Online (Sandbox Code Playgroud)

本周的Wedesday

moment().startOf('week').add('days', 3)
Run Code Online (Sandbox Code Playgroud)

  • 注意,`moment()。add('days',3)`已在最新版本的moment中使用。现在应该是`moment()。add(3,'days')` (2认同)