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

时间:2015-04-15 14:18:09

标签: swift time

您好我正在尝试检查当前时间是否在时间范围内,例如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

12 个答案:

答案 0 :(得分:24)

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

下面是一些游乐场代码,它使用Calendar对象获取当前日期的日/月/年,并添加所需的小时/分钟组件,然后为这些组件生成日期。

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

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

编辑#3:

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

@ CodenameDuchess' answer使用系统函数date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:)

使用该功能,代码可以简化为:

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

旧的(斯威夫特2)答案如下:历史完整性:

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&#34;开箱即用&#34;。

因此,我们可以删除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")
}

答案 1 :(得分:13)

在Swift 3.0中,您可以使用新的日期值类型,并直接与==,&gt;,&lt;进行比较。等

    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

    }

非常方便。

答案 2 :(得分:6)

Swift 3

这是一个通过比较当前时间是否在给定时间范围内来返回String的函数。在游乐场中运行它并根据您自己的需要进行调整。

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 :(得分:4)

您可以从今天的日期获取年,月和日,将这些日期时间字符串附加到日期时间字符串以构建新的Date对象。然后compare todaysDate生成Datelet 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 个对象:

{{1}}

有关Swift 2的答案,请参阅previous revision of this answer

答案 4 :(得分:2)

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

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

答案 5 :(得分: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

答案 6 :(得分:1)

您可以使用compare中的NSDate方法:它会返回您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

答案 7 :(得分:1)

检查此链接

要知道如何快速使用dateformator,请检查下面的链接

enter image description here

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

答案 8 :(得分:0)

你可以像这样比较日期。

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

答案 9 :(得分:0)

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

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"

并从那里继续......

答案 10 :(得分:0)

以下解决方案从系统获取当前时间,然后检查是否存在该范围。 在我的情况下,时间范围是上午8:00至下午5:00  适用于Swift 4.2的解决方案

SELECT * FROM `TEST`
WHERE _vtype='JSON' AND _ktype='BYTES'
AND _sample=2 AND _sampleWindow=200 AND payload.source_order_id='3411976911924'



 Error : "Invalid syntax at line=3 and column=41.Invalid syntax for 'payload.source_order_id'. Field 'payload' resolves to primitive type STRING.

答案 11 :(得分:0)

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