how to check if time is within a specific range in swift

前端 未结 11 1189
一整个雨季
一整个雨季 2020-12-05 03:24

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

相关标签:
11条回答
  • 2020-12-05 03:53

    The Following soltion get current time from the system and then check it exist that range or not . In my case time range is 8:00 am to 5:00 pm The Solution Valid for 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
    }
    
    0 讨论(0)
  • 2020-12-05 03:55

    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
    
    0 讨论(0)
  • 2020-12-05 03:58

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

    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
    

    See previous revision of this answer for Swift 2 answer.

    0 讨论(0)
  • 2020-12-05 04:01
    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")
    
    0 讨论(0)
  • check this link

    to know that how to use dateformator in swift please check the link below

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

    0 讨论(0)
提交回复
热议问题