简体   繁体   English

有没有办法在一段时间后使用 date-fns 或 JavaScript 从数组中返回项目

[英]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.我目前在我的 Angular 应用程序中使用date-fns fns 库,并且我正在使用名为isWeekend的助手从仅在周末的数组中返回一些时隙项。

However, I can't find a way to return the Weekend items after a certain time such as 'after 1pm'.但是,我找不到在某个时间(例如“下午 1 点之后”)之后归还周末商品的方法。

Please see below:请看下面:

  • There are two dates with a time after 13:00:00 (1 PM)有两个日期的时间在 13:00:00(下午 1 点)之后
  • There are two dates with a time before 13:00:00 (1 PM)有两个日期的时间在 13:00:00(下午 1 点)之前

I need to adjust my filter to accommodate for the times which are after 13:00:00 (1 PM) and on the weekend .我需要调整过滤器以适应13:00:00(下午 1 点)之后周末的时间。

 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.您可以使用同一库的getHours function 提取日期的“小时”部分,然后查看它返回的数字是否为 13 或更高。 Combined with your existing usage of isWeekend , your filter is quite simple.结合您现有的isWeekend用法,您的过滤器非常简单。

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>

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

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