SQL(?):计算两个日期时间值之间的时间

发布于 2024-07-06 11:35:30 字数 386 浏览 10 评论 0原文

当我只需要计算 08:00:00-16:00:00 之间的时间时,计算从 MySQL 获取的两个日期时间值之间的时间的最佳方法是什么。

例如,如果我的值是 2008-10-13 18:00:00 和 2008-10-14 10:00:00,那么时间差应该是 02:00:00。

我可以使用 SQL 来完成此操作吗?或者最好的方法是什么? 我正在构建一个网站并使用 PHP。

谢谢您的回答。

编辑:确切的事情是,我正在尝试计算“票”在工作时间内处于特定状态的时间。 时间可能需要几周。

EDIT2:我计算实际时差没有问题,但减去每天的休息时间 00:00:00-08:00:00 和 16:00:00-00:00:00 。

-萨穆里

What is the best way to count the time between two datetime values fetched from MySQL when I need to count only the time between hours 08:00:00-16:00:00.

For example if I have values 2008-10-13 18:00:00 and 2008-10-14 10:00:00 the time difference should be 02:00:00.

Can I do it with SQL or what is the best way to do it? I'm building a website and using PHP.

Thank you for your answers.

EDIT: The exact thing is that I'm trying to count the time a "ticket" has been in a specific state during working hours. The time could be like a couple weeks.

EDIT2: I have no problems counting the actual time difference, but substracting that off-time, 00:00:00-08:00:00 and 16:00:00-00:00:00 per day.

-Samuli

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

逆流 2024-07-13 11:35:30

TIMEDIFF 函数

TIMEDIFF() 返回 expr1 – expr2
表示为时间值。 表达式 1 和
expr2 是时间或日期和时间
表达式,但两者都必须是
相同类型。

mysql> SELECT TIMEDIFF('2000:01:01 00:00:00',
    ->                 '2000:01:01 00:00:00.000001');
        -> '-00:00:00.000001'
mysql> SELECT TIMEDIFF('2008-12-31 23:59:59.000001',
    ->                 '2008-12-30 01:01:01.000002');
        -> '46:58:57.999999'

The TIMEDIFF function

TIMEDIFF() returns expr1 – expr2
expressed as a time value. expr1 and
expr2 are time or date-and-time
expressions, but both must be of the
same type.

mysql> SELECT TIMEDIFF('2000:01:01 00:00:00',
    ->                 '2000:01:01 00:00:00.000001');
        -> '-00:00:00.000001'
mysql> SELECT TIMEDIFF('2008-12-31 23:59:59.000001',
    ->                 '2008-12-30 01:01:01.000002');
        -> '46:58:57.999999'
辞慾 2024-07-13 11:35:30

我认为你应该在自己的代码中计算差异,而不是使用更复杂的 SQL 语句,因为:

  • 该计算似乎是你的业务逻辑的一部分。 如果将其与业务代码的其余部分集成,似乎更容易维护。
  • 数据库通常是瓶颈,因此不要加载超出需要的内容。

I think you should calculate the difference in your own code instead of using a more-complex SQL sentence because:

  • That calculation seems to be part of your business logic. It seems easier to maintain if you integrate it with the rest of your business code.
  • The database is often the bottleneck, so don't load it more than needed.
氛圍 2024-07-13 11:35:30

中会更快

您可能想在 PHP 中尝试一下,但我认为在 DB 代码 返回数组中的差异

You may want to try it in PHP, but I'm thinking it'll be faster in DB

code to return difference in an array

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文