0

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!

  • What do you define as "current week"? – Aplet123 Mar 30 '20 at 21:12
  • The start of the week is `moment().startOf('week')`, it seems you got that part. The end of the week is that plus 7 days. So now check if the day being passed in is greater than or equal to the start of the week and also less than the last day of the week. – Igor Mar 30 '20 at 21:13

1 Answers1

0

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.

bkelley
  • 112
  • 9
  • Based on your follow up question I have updated my answer to include how to figure out the day of the week, and therefore, how many days are left in the week. The momentjs library is quite robust and many functions are available to handle most situations. I encourage you to take a look at the [documentation](https://momentjs.com/docs/) as it is quite detailed with plenty of examples. – bkelley Mar 31 '20 at 14:43