Как проверить, находится ли время в определенном диапазоне в быстром
Привет. Я пытаюсь проверить, находится ли текущее время в пределах временного диапазона, например, с 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
Ответы
Ответ 1
Есть много способов сделать это. Лично мне не нравится работать со строками, если я могу избежать этого. Я бы предпочел иметь дело с компонентами даты.
Ниже приведен некоторый код игровой площадки, который использует объект Calendar для получения дня/месяца/года текущей даты, добавляет нужные компоненты часа/минуты, а затем генерирует дату для этих компонентов.
Он создает даты для 8:00 и 16:30, а затем сравнивает даты, чтобы увидеть, попадает ли текущая дата/время в этот диапазон.
Это дольше, чем код других людей, но я думаю, что стоит научиться делать вычисления с датами, используя календарь:
РЕДАКТИРОВАТЬ № 3:
Этот ответ давным-давно. Я оставлю старый ответ ниже, но вот текущее решение:
В ответе @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")
}
Для исторической полноты следует старый (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 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")
}
РЕДАКТИРОВАТЬ:
Код в этом ответе изменил LOT для Swift 3.
Вместо того чтобы использовать NSDate
, это имеет смысл для нас родной Date
объекта и Date
объекты Equatable
и Comparable
"из коробки".
Таким образом, мы можем избавиться от Equatable
и Comparable
расширений и определений для <
, >
и =
операторов.
Затем нам нужно сделать немало настроек синтаксиса в функции 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 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")
}
Ответ 2
В Swift 3.0 вы можете использовать новый тип значения Date и напрямую сравнивать с ==, > , < и т.д.
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
}
Очень удобно.
Ответ 3
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
}
Ответ 4
Вы можете получить год, месяц и день с даты сегодняшнего дня, добавить их в эти строки даты и времени для создания новых объектов 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 date is inbetween these two resulting 'NSDate' objects
let isInRange = todaysDate > startDate && todaysDate < endDate
Смотрите предыдущую версию этого ответа для Swift 2 ответа.
Ответ 5
Вот какой код я использую в одном из моих текущих проектов. Просто установите время запуска как 8:00, время окончания - 16:30, а время - как текущее время.
func isTimeStampCurrent(timeStamp:NSDate, startTime:NSDate, endTime:NSDate)->Bool{
if timeStamp.earlierDate(endTime) == timeStamp && timeStamp.laterDate(startTime) == timeStamp{
return true
}
return false
}
Ответ 6
Вы можете сделать 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
Ответ 7
Вы можете использовать метод compare
из NSDate
: он вернет NSComparisonResult
(OrderedSame
, OrderedAscending
или OrderedDescending
), который вы можете проверить по датам начала и окончания:
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
Ответ 8
проверьте эту ссылку
Чтобы узнать, как использовать dateformator в Swift, пожалуйста, проверьте ссылку ниже
![enter image description here]()
https://nsscreencast.com/episodes/367-dates-and-times
Ответ 9
Вы можете сравнить дату, подобное этому.
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
}
}
Ответ 10
также, приведенное ниже решение выглядит коротким, если я хочу посмотреть, находится ли время в определенном диапазоне в течение дня
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"
и продолжайте оттуда...
Ответ 11
Следующее решение получает текущее время из системы, а затем проверяет, существует ли этот диапазон или нет. В моем случае временной диапазон - с 8:00 до 17: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
}