简体   繁体   English

具有特定条件时间开始和时间结束的 Date_diff

[英]Date_diff with specific condition time start and time end

is it possible to have date_diff with specific start and end time? date_diff 是否可以有特定的开始和结束时间?

let say my store are open from 8AM - 10PM, which is 14 Hours.假设我的商店营业时间为上午 8 点至晚上 10 点,即 14 小时。 and I have a lot of stuff to sell during that time.那段时间我有很多东西要卖。 One of the SKU is out of stock from 2022-11-01 06.00 PM until tomorrow 2022-11-02 11.00 AM.其中一个 SKU 从 2022-11-01 下午 6 点到明天 2022-11-02 上午 11 点缺货。

Instead of calculate 24 hours, I just want to calculate only from opening store until it closed or until its restock.而不是计算 24 小时,我只想计算从开店到关门或到补货。 Meaning from 6PM to 11AM is 8 Hours意思是从下午 6 点到上午 11 点是 8 小时

my query我的查询

select date_diff('2022-11-02 11.00 AM', '2022-11-02 06.00 PM', hour) from table

with the result 17 hours instead of 8 hours结果是 17 小时而不是 8 小时

There isn't a way to configure DATE_DIFF to do this for you, but it's possible to do what you want, with some effort .没有办法配置DATE_DIFF来为您执行此操作,但可以通过一些努力来执行您想要的操作

You should convert your dates to timestamps ( TIMESTAMP(yourdate) or CAST(yourdate AS TIMESTAMP) ) and use TIMESTAMP_DIFF instead.您应该将日期转换为时间戳( TIMESTAMP(yourdate)CAST(yourdate AS TIMESTAMP) )并改用TIMESTAMP_DIFF

This will allow you to work with smaller intervals than days.这将允许您以比几天更短的间隔工作。

For your calculation, you ultimately need to find the total time difference between the two timestamps and then subtract the out-of-hours timeframe.对于您的计算,您最终需要找到两个时间戳之间的总时间差,然后减去非工作时间的时间范围。

However, calculating the latter is not as simple as taking the difference in days and multiplying by 8 hours (10pm-6am), because your out-of-hours calculation has to account for weekends and possibly holidays etc. Hence it can get quite complex, which is where the solution in my first link might come in.然而,计算后者并不像计算天数差乘以 8 小时(晚上 10 点到早上 6 点)那么简单,因为您的非工作时间计算必须考虑周末和可能的假期等。因此它可能会变得非常复杂,这是我第一个链接中的解决方案可能出现的地方。

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

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