算法需要计算两个时间之间差 [英] Algorithm needed to calculate difference between two times

查看:124
本文介绍了算法需要计算两个时间之间差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小时的选择下拉 0-23 和分钟选择下拉 0-59 启动时间结束时间分别为(这样四个控件)。

I have an hour selection drop down 0-23 and minutes selection drop down 0-59 for Start time and End time respectively (so four controls).

我在寻找一种算法使用这四个值来计算时间差。

I'm looking for an algorithm to calculate time difference using these four values.

由于他们不存储在花哨的日期/时间选择控件,我不认为我可以使用任何标准的日期/时间处理函数。

Since they're not stored in fancy date/time selection controls, I don't think I can use any standard date/time manipulation functions.

我如何计算两个时间之间的区别是什么?

How do I calculate the difference between the two times?

推荐答案

这个伪code给你的算法工作,在几分钟内的差异。

This pseudo-code gives you the algorithm to work out the difference in minutes.

它假定,如果开始时间结束时间之后,开始时间竟是在previous一天。

It assumes that, if the start time is after the end time, the start time was actually on the previous day.

startx = starthour * 60 + startminute
endx = endhour * 60 + endminute
duration = endx - startx
if duration < 0:
    duration = duration + 1440

运行startx endx 值是自午夜的分钟数。

The startx and endx values are the number of minutes since midnight.

这基本上是这样做的:

  • 获取从一天开始时间开始的分钟数。
  • 获取从一天结束时开始的分钟数。
  • 减去前者从后者。
  • 如果结果是否定的,在一天中添加分钟数。

别那么肯定,虽然你不能使用日期/时间处理函数。您可能会发现,你可以很容易地构造一个日期/时间,并计算与类似的差异:

Don't be so sure though that you can't use date/time manipulation functions. You may find that you could easily construct a date/time and calculate differences with something like:

DateTime startx = new DateTime (1,1,2010,starthour,startminute,0);
DateTime endx   = new DateTime (1,1,2010,endhour  ,endminute  ,0);
Integer duration = DateTime.DiffSecs (endx,startx) / 60;
if (duration < 0)
    duration = duration + 1440;

尽管它可能并不需要您的简单场景。我会坚持使用伪code我给上面的,除非你发现自己做了一些棘手的日期/时间操作。

although it's probably not needed for your simple scenario. I'd stick with the pseudo-code I gave above unless you find yourself doing some trickier date/time manipulation.

如果你再要转时间(分钟)到小时和分钟:

If you then want to turn the duration (in minutes) into hours and minutes:

durHours = int(duration / 60)
durMinutes = duration % 60 // could also use duration - (durHours * 60)

这篇关于算法需要计算两个时间之间差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆