Designing non-overlapping date-time events

让人想犯罪 __ 提交于 2019-11-28 14:44:08

It is very common when working with date-time ranges that you use a range that is inclusive at the start and exclusive at the end. For example:

(using ISO8601 formatting)

Start                  End
2013-04-29T01:00:00Z - 2013-04-29T02:00:00Z
2013-04-29T02:00:00Z - 2013-04-29T03:00:00Z

A value is in range when it is less than or equal to the start, and greater than (but not equal to) the end. In the example above, 02:00 belongs to the second range, not the first one. In other words:

Start <= value < End 

Or equivalently,

Start <= value  AND  End > value

In Mathematics, using Interval Notation, this is known as a "half-open" interval.

[Start, End)

This is always a better approach than the idea of using a value like 01:59:59. Consider if I were to subtract End - Start to get a duration. I would expect the answer be one hour, not 59 minutes and 59 seconds.

Most examples use the terms Start/End, but sometimes you will see Begin/End or Start/Stop. Personally, I think the best set of terms to use when you have an inclusive/exclusive range is Start/Until. It has the added advantage of both terms being 5 characters, lining up alphabetically, and explicitly conveying that the end date is exclusive.

Also, when you are talking about distinct events, you should record your times as UTC to prevent confusion around time zones. This is even important for local applications, as many time zones go through daylight savings transitions. You don't want the values you record in the database to be ambiguous. In MySQL, you can use the TIMESTAMP data type to make sure values are stored as UTC, or you can use the DATETIME data type if you can be sure you are working with UTC values in your application code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!