简体   繁体   中英

Is there a way to return items from an array after a certain time using date-fns or JavaScript

I am currently using the date-fns library in my Angular application and I am using the helper called isWeekend to return some time slot items from an array that only fall on a weekend.

However, I can't find a way to return the Weekend items after a certain time such as 'after 1pm'.

Please see below:

  • There are two dates with a time after 13:00:00 (1 PM)
  • There are two dates with a time before 13:00:00 (1 PM)

I need to adjust my filter to accommodate for the times which are after 13:00:00 (1 PM) and on the weekend .

 const days = [ { date: "Sun Jul 25 2020 15:30:00 GMT+0100 (British Summer Time)" }, { date: "Sun Jul 25 2020 19:00:00 GMT+0100 (British Summer Time)" }, { date: "Sat Jul 25 2020 05:00:00 GMT+0100 (British Summer Time)" }, { date: "Sat Jul 25 2020 02:00:00 GMT+0100 (British Summer Time)" } ]; const filteredDays = days.filter((day) => { console.log(dateFns.isWeekend(day.date)); // Need a solution for dateFns.isWeekend and after 13:00:00 or 1 PM });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>

You can extract the 'hours' component of the date with the same library's getHours function, and then see if the number it returns is 13 or higher. Combined with your existing usage of isWeekend , your filter is quite simple.

Note: This library is going to run both of those functions based on the user's current locale, while your dates are specifying a timezone. Just something to keep in mind.

 const days = [ { date: "Sun Jul 25 2020 15:30:00 GMT+0100 (British Summer Time)" }, { date: "Sun Jul 25 2020 19:00:00 GMT+0100 (British Summer Time)" }, { date: "Sat Jul 25 2020 05:00:00 GMT+0100 (British Summer Time)" }, { date: "Sat Jul 25 2020 02:00:00 GMT+0100 (British Summer Time)" } ]; const filteredDays = days.filter((day) => { return dateFns.isWeekend(day.date) && dateFns.getHours(day.date) >= 13; }); console.log(filteredDays);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>

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