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条回答
不美不萌又怎样
2楼-- · 2019-01-17 05:39

You can compare date like this.

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
 }
}
查看更多
贼婆χ
3楼-- · 2019-01-17 05:43

You can get year, month, and day from today's date, append those to those date time strings to build new NSDate objects. Then compare the todaysDate to those two resulting NSDate objects:

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

// convert strings to `NSDate` objects

let formatter = NSDateFormatter()
formatter.dateFormat = "HH:mm"
let startTime = formatter.dateFromString(startString)
let endTime = formatter.dateFromString(endString)

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

let calendar = NSCalendar.currentCalendar()

let startComponents = calendar.components([.Hour, .Minute], fromDate: startTime!)
let endComponents = calendar.components([.Hour, .Minute], fromDate: endTime!)

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

let nowComponents = calendar.components([.Month, .Day, .Year], fromDate: 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`

let startDate = calendar.dateFromComponents(startComponents)
let endDate = calendar.dateFromComponents(endComponents)

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

let isInRange = todaysDate.compare(startDate!) != .OrderedAscending && todaysDate.compare(endDate!) != .OrderedDescending
查看更多
疯言疯语
4楼-- · 2019-01-17 05:45

also, the solution below looks short if i want to see if the time is in a specific range during day

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)

i guess you could modify it, to check for example, if the months are in certain ranges too, e.g:

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

and continue from there...

查看更多
登录 后发表回答