使用的时刻。找到当前星期的具体日期

时间:2022-09-26 11:15:13

Finding the date of a specific day of the current week with Moment.js

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

在javascript中有很多方法可以操作日期。我一直在寻找一种最简单、最简单的方法来实现这一点,而不需要冗长、难看的代码,因此有人向我展示了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.

我想使用当前日期来查找当前周的具体日期。到目前为止,我的尝试包括计算当前的天数(0-6天)和检查它与周一(第一天)之间的天数之差,这一点都不对。

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.

我不希望使用原生的JS日期功能,在我所看到的每一种情况下都会产生丑陋的、混乱的代码。

2 个解决方案

#1


54  

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

本周的wedesday

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

#2


1  

It's not longer possible to use just a string (e. g. 'isoweek'), we need to use it like this:

仅仅使用一个字符串是不可能的。“isoweek”),我们需要这样使用它:

import * as moment from 'moment';
import { unitOfTime } from 'moment';

moment().startOf('isoweek' as unitOfTime.StartOf);

#1


54  

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

本周的wedesday

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

#2


1  

It's not longer possible to use just a string (e. g. 'isoweek'), we need to use it like this:

仅仅使用一个字符串是不可能的。“isoweek”),我们需要这样使用它:

import * as moment from 'moment';
import { unitOfTime } from 'moment';

moment().startOf('isoweek' as unitOfTime.StartOf);