嗨,我想检查当前时间是否在一个时间范围内,比如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
Run Code Online (Sandbox Code Playgroud)
Dun*_*n C 28
有很多方法可以做到这一点.就个人而言,我不喜欢使用字符串,如果我可以避免它.我宁愿处理日期组件.
下面是一些操场代码,它使用Calendar对象获取当前日期的日/月/年,并添加所需的小时/分钟组件,然后为这些组件生成日期.
它创建8:00和16:30的日期,然后比较日期以查看当前日期/时间是否在该范围内.
它比其他人的代码更长,但我认为值得学习如何使用日历进行日期计算:
这个答案来自很久以前.我将在下面留下旧的答案,但这是目前的解决方案:
@CodenameDuchess的回答使用系统函数, 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")
}
Run Code Online (Sandbox Code Playgroud)
以下是旧的(Swift 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")
}
Run Code Online (Sandbox Code Playgroud)
这个答案中的代码改变了很多Swift 3.
而不是使用的NSDate
,它更有意义,我们本地Date
的对象,Date
对象是Equatable
和Comparable
"开箱即用".
因此,我们可以摆脱的Equatable
和Comparable
扩展以及定义<
,>
和=
运营商.
然后我们需要对dateAt
函数中的语法进行大量调整,以遵循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")
}
Run Code Online (Sandbox Code Playgroud)
Cod*_*ess 15
在Swift 3.0中,您可以使用新的Date值类型并直接与==,>,<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
}
Run Code Online (Sandbox Code Playgroud)
非常方便.
您可以从今天的日期获取年、月和日,将它们附加到这些日期时间字符串以构建新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
Run Code Online (Sandbox Code Playgroud)
有关Swift 2 答案,请参阅此答案的先前修订版。
以下解决方案从系统获取当前时间,然后检查它是否存在该范围。在我的情况下,时间范围是上午 8:00 到下午 5:00 适用于 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
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
23439 次 |
最近记录: |