简体   繁体   English

是本周的某一天吗? 瞬间JS

[英]Is it a day in the current week? Moment JS

I have one problem.我有一个问题。 Can you tell me how to check does it day in the current week?你能告诉我如何检查本周的一天吗?

I am working on some service for a weather forecast.我正在为天气预报提供一些服务。 I have a current day but must check does it in the current week.我有今天,但必须检查是否在本周。 Only what I know is that I must use 'isSame' function from Moment JS.我只知道我必须使用 Moment JS 的“isSame”函数。 This is my line of code.这是我的代码行。

 if(this.conversation.payload.grain==="week" && moment().startOf('week').isSame(this.conversation.payload.forecastTime))

"forecastTime" is a current day. “forecastTime”是当前日期。 However, the condition is not good and does not enter the if loop.但是条件不好,没有进入if循环。

Thank you!谢谢!

This is assuming your forecastedDate is an actual javascript date or a moment object.这是假设您的 predictedDate 是实际的 javascript 日期或时刻对象。

The isSame function also takes in a granularity parameter. isSame 函数还接受粒度参数。

Just add the 'week' parameter to the isSame method like so:只需将 'week' 参数添加到 isSame 方法中,如下所示:

if(this.conversation.payload.grain==="week" &&
    moment().startOf("week").isSame(this.conversation.payload.forecastTime, "week"))

To get the day of the week is easily done with the momentjs library.使用 momentjs 库可以轻松获取星期几。

This will give you a day of the week based on the locale:这将根据语言环境为您提供一周中的一天:

var dayOfWeek = moment(this.conversation.payload.forecastTime).weekday()

For example, if the locale uses Monday as the first day of the week then 0 = Monday and 6 = Sunday.例如,如果语言环境使用星期一作为一周的第一天,则 0 = 星期一,6 = 星期日。 Please keep in mind that the value you recieve will change based on the current locale.请记住,您收到的值将根据当前区域设置而变化。

If you don't want the value to change based on locale but always want to receive a Monday-Sunday value use isoWeekday():如果您不希望根据区域设置更改值,但始终希望收到周一至周日的值,请使用 isoWeekday():

var dayOfWeek = moment(this.conversation.payload.forecastTime).isoWeekday()

This will give you an integer 1-7.这会给你一个整数 1-7。 1 = Monday, 7 = Sunday. 1 = 星期一,7 = 星期日。

So, for example, if the above code returned 4, you would know that it was Thursday.因此,例如,如果上面的代码返回 4,您就会知道今天是星期四。

For more details on the weekday(), isoWeekday, and day() functions, check out the momentjs docs .有关 weekday()、isoWeekday 和 day() 函数的更多详细信息,请查看momentjs 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM