how to check if time is within a specific range in

2019-01-17 04:54发布

Hi I am trying to check if the current time is within a time range, say 8:00 - 16:30. My code below shows that I can obtain the current time as a string, but I am unsure how I can use this value to check if it is inside the time range specified above. Any help would be greatly appreciated!

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

标签: swift time
9条回答
SAY GOODBYE
2楼-- · 2019-01-17 05:24

Swift 3

This is a function that returns a String by comparing if the current time is within a range of given times. Run it in a Playground and adapt it to your own needs.

func updateGreeting() -> String {

var greeting = String()

//date formatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"

// Get current time and format it to compare
var currentTime = Date()
let currentTimeStr = dateFormatter.string(from: currentTime)
currentTime = dateFormatter.date(from: currentTimeStr)!

//Times array
let startTimes = ["5:00 AM", //Morning
    "11:00 AM", //Aftenoon
    "5:00 PM", //Evening
    "9:00 PM" //Nigth
]

let morning = 0
let afternoon = 1
let evening = 2
let night = 3

var dateTimes = [Date]()

//create an array with the desired times
for i in 0..<startTimes.count{
    let dateTime = dateFormatter.date(from: startTimes[i])
    print(dateTime!)
    dateTimes.append(dateTime!)
}

if currentTime >= dateTimes[morning] && currentTime < dateTimes[afternoon]   {
    greeting = "Good Morning!"
}
if currentTime >= dateTimes[afternoon] && currentTime < dateTimes[evening]   {
    greeting = "Good Afternoon!"
}
if currentTime >= dateTimes[evening] && currentTime <= dateTimes[night]   {
    greeting = "Good Evening"
}
if currentTime >= dateTimes[night] && currentTime < dateTimes[morning]   {
    greeting = "Good Night"
}

return greeting

}

查看更多
三岁会撩人
3楼-- · 2019-01-17 05:24

Here is some code I use in one of my current projects. Just set start time as 8:00, end time as 16:30, and timeStamp as current time.

func isTimeStampCurrent(timeStamp:NSDate, startTime:NSDate, endTime:NSDate)->Bool{
    if timeStamp.earlierDate(endTime) == timeStamp && timeStamp.laterDate(startTime) == timeStamp{
        return true
    }
    return false
}
查看更多
Emotional °昔
4楼-- · 2019-01-17 05:33

In Swift 3.0 you can use the new Date value type and compare directly with ==,>,< etc

    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

    }

Very handy indeed.

查看更多
甜甜的少女心
5楼-- · 2019-01-17 05:33

You can use the compare method from NSDate: it will return an NSComparisonResult (OrderedSame, OrderedAscending or OrderedDescending) that you can check against your start and end dates:

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
查看更多
姐就是有狂的资本
6楼-- · 2019-01-17 05:34

You could make NSDate conform to the Comparable protocol to be able to use the ==, !=, <=, >=, > and < operators. For example:

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
}

To use this to check a date was within two dates you could use:

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

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

Here are a few more examples of how to use the operators with NSDate:

olderDate < newerDate  // True
olderDate > newerDate  // False
olderDate != newerDate // True
olderDate == newerDate // False
查看更多
别忘想泡老子
7楼-- · 2019-01-17 05:36

There are lots of ways to do this. Personally, I don't like working with strings if I can avoid it. I'd rather deal with date components.

Below is some playground code that uses a Calendar object to get the day/month/year of the current date, and adds the desired hour/minute components, and then generates a date for those components.

It creates dates for 8:00 and 16:30, and then compares the dates to see if the current date/time falls in that range.

It's longer than other people's code, but I think it's worth learning how to do calculations with dates using a Calendar:

EDIT #3:

This answer is from a long time ago. I'll leave the old answer below, but here is the current solution:

@CodenameDuchess' answer uses a system function, date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:)

Using that function, the code can be simplified to this:

import UIKit

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)!

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

The old (Swift 2) answer follows, for historical completeness:

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")
}

EDIT:

The code in this answer has changed a LOT for Swift 3.

Instead of using NSDate, it makes more sense to us the native Date object, and Date objects are Equatable and Comparable "out of the box".

Thus we can get rid of the Equatable and Comparable extensions and the definitions for the <, > and = operators.

Then we need to do a fair amount of tweaking of the syntax in the dateAt function to follow Swift 3 syntax. The new extension looks like this in Swift 3:

Swift 3 version:

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")
}
查看更多
登录 后发表回答