一尘不染

如何快速检查时间是否在特定范围内

swift

嗨,我正在尝试检查当前时间是否在某个时间范围内,例如8:00-16:30。下面的代码显示可以将当前时间作为字符串获取,但是不确定如何使用此值来检查它是否在上面指定的时间范围内。任何帮助将不胜感激!

var todaysDate:NSDate = NSDate()
var dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
var dateInFormat:String = dateFormatter.stringFromDate(todaysDate)
println(dateInFormat) // 23:54

阅读 313

收藏
2020-07-07

共1个答案

一尘不染

有很多方法可以做到这一点。就我个人而言,如果可以避免的话,我不喜欢使用字符串。我宁愿处理日期组件。

下面的代码创建的日期为8:00和16:30,然后比较日期以查看当前日期/时间是否在该范围内。

它比其他人的代码长,但是我认为值得学习如何使用Calendar进行日期计算:

编辑#3:

这个答案来自很久以前。我将在下面保留旧答案,但这是当前解决方案:

@CodenameDuchess的答案使用系统功能,
date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:)

使用该函数,代码可以简化为:

import UIKit

// The function `Calendar.date(bySettingHour:minute:second)` lets you 
// create date objects for a given time in the same day of given date
// For example, 8:00 today

let calendar = Calendar.current
let now = Date()
let eight_today = calendar.date(
  bySettingHour: 8,
  minute: 0,
  second: 0,
  of: now)!

let four_thirty_today = calendar.date(
  bySettingHour: 16,
  minute: 30,
  second: 0,
  of: now)!

// In recent versions of Swift Date objectst are comparable, so you can 
// do greater than, less than, or equal to comparisons on dates without
// needing a date extension

if now >= eight_today &&
  now <= four_thirty_today
{
  print("The time is between 8:00 and 16:30")
}

为了历史的完整性,下面是旧的(Swift 2)答案:

此代码使用Calendar对象获取当前日期的日/月/年,并添加所需的小时/分钟组成部分,然后为这些组成部分生成日期。

import UIKit
//-------------------------------------------------------------
//NSDate extensions.
extension NSDate
{
  /**
  This adds a new method dateAt to NSDate.

  It returns a new date at the specified hours and minutes of the receiver

  :param: hours: The hours value
  :param: minutes: The new minutes

  :returns: a new NSDate with the same year/month/day as the receiver, but with the specified hours/minutes values
  */
  func dateAt(#hours: Int, minutes: Int) -> NSDate
  {
    let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!

    //get the month/day/year componentsfor today's date.

    println("Now = \(self)")

    let date_components = calendar.components(
      NSCalendarUnit.CalendarUnitYear |
        NSCalendarUnit.CalendarUnitMonth |
        NSCalendarUnit.CalendarUnitDay,
      fromDate: self)

    //Create an NSDate for 8:00 AM today.
    date_components.hour = hours
    date_components.minute = minutes
    date_components.second = 0

    let newDate = calendar.dateFromComponents(date_components)!
        return newDate
  }
}
//-------------------------------------------------------------
//Tell the system that NSDates can be compared with ==, >, >=, <, and <= operators
extension NSDate: Equatable {}
extension NSDate: Comparable {}

//-------------------------------------------------------------
//Define the global operators for the 
//Equatable and Comparable protocols for comparing NSDates

public func ==(lhs: NSDate, rhs: NSDate) -> Bool
{
  return lhs.timeIntervalSince1970 == rhs.timeIntervalSince1970
}

public func <(lhs: NSDate, rhs: NSDate) -> Bool
{
  return lhs.timeIntervalSince1970 < rhs.timeIntervalSince1970
}
public func >(lhs: NSDate, rhs: NSDate) -> Bool
{
  return lhs.timeIntervalSince1970 > rhs.timeIntervalSince1970
}
public func <=(lhs: NSDate, rhs: NSDate) -> Bool
{
  return lhs.timeIntervalSince1970 <= rhs.timeIntervalSince1970
}
public func >=(lhs: NSDate, rhs: NSDate) -> Bool
{
  return lhs.timeIntervalSince1970 >= rhs.timeIntervalSince1970
}
//-------------------------------------------------------------

let now = NSDate()
let eight_today = now.dateAt(hours: 8, minutes: 0)
let four_thirty_today = now.dateAt(hours:16, minutes: 30)

if now >= eight_today &&
  now <= four_thirty_today
{
  println("The time is between 8:00 and 16:30")
}

编辑:

此答案中的代码已更改Swift 3的很多。

而不是使用的NSDate,它更有意义,我们本地Date的对象,Date对象是EquatableComparable“开箱即用”。

因此,我们可以摆脱的EquatableComparable扩展以及定义<>=运营商。

然后,我们需要对dateAt函数中的语法进行大量调整以遵循Swift 3语法。新的扩展在Swift 3中如下所示:

Swift 3版本:

import Foundation

extension Date
{

  func dateAt(hours: Int, minutes: Int) -> Date
  {
    let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!

    //get the month/day/year componentsfor today's date.


    var date_components = calendar.components(
      [NSCalendar.Unit.year,
       NSCalendar.Unit.month,
       NSCalendar.Unit.day],
      from: self)

    //Create an NSDate for the specified time today.
    date_components.hour = hours
    date_components.minute = minutes
    date_components.second = 0

    let newDate = calendar.date(from: date_components)!
    return newDate
  }
}


let now = Date()
let eight_today = now.dateAt(hours: 8, minutes: 0)
let four_thirty_today = now.dateAt(hours: 16, minutes: 30)

if now >= eight_today &&
  now <= four_thirty_today
{
  print("The time is between 8:00 and 16:30")
}
2020-07-07