如何检查时间是否在 swift 的特定范围内

how to check if time is within a specific range in 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

这是我在当前项目之一中使用的一些代码。只需将开始时间设置为 8:00,结束时间设置为 16:30,将时间戳设置为当前时间即可。

func isTimeStampCurrent(timeStamp:NSDate, startTime:NSDate, endTime:NSDate)->Bool{
    timeStamp.earlierDate(endTime) == timeStamp && timeStamp.laterDate(startTime) == timeStamp
}

您可以使用 NSDate 中的 compare 方法:它将 return 一个 NSComparisonResultOrderedSameOrderedAscendingOrderedDescending),您可以检查您的开始和结束日期:

let dateMaker = NSDateFormatter()
dateMaker.dateFormat = "yyyy/MM/dd HH:mm:ss"
let start = dateMaker.dateFromString("2015/04/15 08:00:00")!
let end = dateMaker.dateFromString("2015/04/15 16:30:00")!

func isBetweenMyTwoDates(date: NSDate) -> Bool {
    if start.compare(date) == .OrderedAscending && end.compare(date) == .OrderedDescending {
        return true
    }
    return false
}

println(isBetweenMyTwoDates(dateMaker.dateFromString("2015/04/15 12:42:00")!)) // prints true
println(isBetweenMyTwoDates(dateMaker.dateFromString("2015/04/15 17:00:00")!)) // prints false

您可以从今天的日期获取年、月和日,将它们附加到那些日期时间字符串以构建新的 Date 对象。然后 compare todaysDate 到那两个结果 Date 对象:

let todaysDate  = Date()
let startString = "8:00"
let endString   = "16:30"

// convert strings to `Date` objects

let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
let startTime = formatter.date(from: startString)
let endTime = formatter.date(from: endString)

// extract hour and minute from those `Date` objects

let calendar = Calendar.current

var startComponents = calendar.dateComponents([.hour, .minute], from: startTime!)
var endComponents = calendar.dateComponents([.hour, .minute], from: endTime!)

// extract day, month, and year from `todaysDate`

let nowComponents = calendar.dateComponents([.month, .day, .year], from: todaysDate)

// adjust the components to use the same date

startComponents.year  = nowComponents.year
startComponents.month = nowComponents.month
startComponents.day   = nowComponents.day

endComponents.year  = nowComponents.year
endComponents.month = nowComponents.month
endComponents.day   = nowComponents.day

// combine hour/min from date strings with day/month/year of `todaysDate`

guard
    let startDate = calendar.date(from: startComponents),
    let endDate = calendar.date(from: endComponents)
else {
    print("unable to create dates")
    return
}

// now we can see if today's date is inbetween these two resulting `NSDate` objects

let isInRange = todaysDate > startDate && todaysDate < endDate

请参阅 previous revision of this answer 以获得 Swift 2 个答案。

您可以使 NSDate 符合 Comparable 协议,以便能够使用 ==!=<=>=>< 运算符。例如:

extension NSDate : Comparable {}

//  To conform to Comparable, NSDate must also conform to Equatable.
//  Hence the == operator.
public func == (lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.compare(rhs) == .OrderedSame
}

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

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

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

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

要使用它来检查日期是否在两个日期之内,您可以使用:

let currentDate = NSDate()
let olderDate   = NSDate(timeIntervalSinceNow: -100)
let newerDate   = NSDate(timeIntervalSinceNow: 100)

olderDate < currentDate && currentDate < newerDate // Returns true

以下是如何使用 NSDate:

运算符的更多示例
olderDate < newerDate  // True
olderDate > newerDate  // False
olderDate != newerDate // True
olderDate == newerDate // False

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

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

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

编辑#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)答案如下:

此代码使用日历对象获取当前日期的 day/month/year,并添加所需的 hour/minute 组件,然后为这些组件生成日期。

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"out of the box".

因此我们可以摆脱 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")
}

在 Swift 3.0 中,您可以使用新的日期值类型并直接与 ==、>、< 等进行比较

let now = NSDate()
let nowDateValue = now as Date
let todayAtSevenAM = calendar.date(bySettingHour: 7, minute: 0, second: 0, of: nowDateValue, options: [])
let todayAtTenPM = calendar.date(bySettingHour: 22, minute: 0, second: 0, of: nowDateValue, options: [])

if nowDateValue >= todayAtSevenAM! &&
   nowDateValue <= todayAtTenPM!
{
    // date is in range
}

确实非常方便。

你可以这样比较日期。

extension NSDate {

func isGreaterThanDate(dateToCompare: NSDate) -> Bool {
    //Declare Variables
    var isGreater = false

    //Compare Values
    if self.compare(dateToCompare) == NSComparisonResult.OrderedDescending {
        isGreater = true
    }

    //Return Result
    return isGreater
}

func isLessThanDate(dateToCompare: NSDate) -> Bool {
    //Declare Variables
    var isLess = false

    //Compare Values
    if self.compare(dateToCompare) == NSComparisonResult.OrderedAscending {
        isLess = true
    }

    //Return Result
    return isLess
}

func equalToDate(dateToCompare: NSDate) -> Bool {
    //Declare Variables
    var isEqualTo = false

    //Compare Values
    if self.compare(dateToCompare) == NSComparisonResult.OrderedSame {
        isEqualTo = true
    }

    //Return Result
    return isEqualTo
}

func addDays(daysToAdd: Int) -> NSDate {
    let secondsInDays: NSTimeInterval = Double(daysToAdd) * 60 * 60 * 24
    let dateWithDaysAdded: NSDate = self.dateByAddingTimeInterval(secondsInDays)

    //Return Result
    return dateWithDaysAdded
}

func addHours(hoursToAdd: Int) -> NSDate {
    let secondsInHours: NSTimeInterval = Double(hoursToAdd) * 60 * 60
    let dateWithHoursAdded: NSDate = self.dateByAddingTimeInterval(secondsInHours)

    //Return Result
    return dateWithHoursAdded
 }
}

此外,如果我想查看白天的时间是否在特定范围内,下面的解决方案看起来很短

var greeting = String()
let date     = Date()
let calendar = Calendar.current
let hour     = calendar.component(.hour, from: date)
//let minutes  = calendar.component(.minute, from: date)
let morning = 3; let afternoon=12; let evening=16; let night=22;

print("Hour: \(hour)")
if morning < hour, hour < afternoon {
    greeting = "Good Morning!"
}else if afternoon < hour, hour < evening{
    greeting = "Good Afternoon!"
}else if evening < hour, hour < night{
    greeting = "Good Evening!"
}else{
    greeting = "Good Night"
}
print(greeting)

我想你可以修改它,例如检查月份是否也在特定范围内,例如:

sum = "Jan"
win = "March"
Spr = "May"
Aut = "Sept"

然后从那里继续...

以下解决方案从系统获取当前时间,然后检查它是否存在于该范围内。 在我的例子中,时间范围是 8:00 am 到 5:00 pm 适用于 Swift 4.2

的解决方案
 func CheckTime()->Bool{
    var timeExist:Bool
    let calendar = Calendar.current
    let startTimeComponent = DateComponents(calendar: calendar, hour:8)
    let endTimeComponent   = DateComponents(calendar: calendar, hour: 17, minute: 00)

    let now = Date()
    let startOfToday = calendar.startOfDay(for: now)
    let startTime    = calendar.date(byAdding: startTimeComponent, to: startOfToday)!
    let endTime      = calendar.date(byAdding: endTimeComponent, to: startOfToday)!

    if startTime <= now && now <= endTime {
        print("between 8 AM and 5:30 PM")
        timeExist = true
    } else {
        print("not between 8 AM and 5:30 PM")
        timeExist = false
    }
    return timeExist
}

检查这个link

要了解如何在 swift 中使用 dateformator,请查看下面的 link

https://nsscreencast.com/episodes/367-dates-and-times

extension Date { 
    /// time returns a double for which the integer represents the hours from 1 to 24 and the decimal value represents the minutes.  
    var time: Double {
        Double(Calendar.current.component(.hour, from: self)) + Double(Calendar.current.component(.minute, from: self)) / 100
    }
}

// usage 
print(9.30...16.30 ~= Date().time ? "If you're on the East Coast, It is during market hours" : "its after hours")