简体   繁体   中英

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. 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. However, the condition is not good and does not enter the if loop.

Thank you!

This is assuming your forecastedDate is an actual javascript date or a moment object.

The isSame function also takes in a granularity parameter.

Just add the 'week' parameter to the isSame method like so:

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.

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. 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():

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

This will give you an integer 1-7. 1 = Monday, 7 = Sunday.

So, for example, if the above code returned 4, you would know that it was Thursday.

For more details on the weekday(), isoWeekday, and day() functions, check out the momentjs docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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