测试当前时间是否在两个TimeIntervals之间

时间:2017-08-30 19:50:40

标签: swift date nsdate nscalendar nstimeinterval

我有2 TimeIntervals,它只代表与日期无关的时间(例如上午8:00和下午5:00)。所以0表示正午夜,在这种情况下,29,040代表8:04 AM。我想检查手机的时间是否在两个TimeIntervals之间。

我发现了一些类似的Stack Overflow问题,但没有一个真正处理TimeIntervals。似乎只是使用start <= Date().timeIntervalSinceReferenceDate <= end或某些东西不起作用,因为它会返回一个巨大的值。

在Swift 3中处理此类情况的最佳方法是什么?

编辑:为了澄清,我不需要担心夏令时等问题。例如,假设用户只希望应用程序中的某些内容在X和Y之间发生,其中X和Y从午夜开始作为TimeInterval值给我。因此,在完成操作之前检查手机的TimeInterval是否在典型的一天午夜之间是否在X和Y之间就足够了。

2 个答案:

答案 0 :(得分:2)

RewriteEngine On RewriteCond %{REQUEST_FILENAME} -d [OR] RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^ - [L] RewriteRule ^([a-z]{2})/([\w-]+)/([\w-]+)/?$ index.php?lang=$1&page=$2&subpage=$3 [QSA,L,NC] RewriteRule ^([a-z]{2})/([\w-]+)/?$ index.php?lang=$1&page=$2 [QSA,L,NC] RewriteRule ^([\w-]+)/([\w-]+)/?$ index.php?page=$1&subpage=$2 [QSA,L] RewriteRule ^([\w-]+)/?$ index.php?page=$1 [QSA,L] returns the number of seconds since Jan 1, 2000 so no doubt it's a huge number.

It's inadvisable to store time as seconds since midnight due to this naggy little thing called Daylight Saving Time. Every year, different countries do it on different days and on different hours. For example, even though Britain and France change their clock on the same day (March 26, 2017), one makes the shift from 1AM to 2AM, the other goes from 2AM to 3AM. That's very easy to make for a mess!

Use +clicked_branch_link:true instead:

integrations@branch.io

答案 1 :(得分:0)

我最终使用DateComponents来计算TimeInterval

let components = Calendar.current.dateComponents(
  [.hour, .minute, .second], from: Date())
guard let seconds = components.second,
  let minutes = components.minute,
  let hours = components.hour else
{
  return false
}
let currentTime = Double(seconds + minutes * 60 + hours * 60 * 60)
return startTime <= currentTime && currentTime <= endTime