comparing time without date swift3
Suggestion using DateComponents
Assuming this given array
let times = ["4:30 AM","1:00 PM","3:20 PM","6:40 PM","9:10 PM"]
Create a date formatter matching the format
let formatter = DateFormatter()
formatter.dateFormat = "h:mm a"Map the time strings to
Date
and immediately toDateComponents
considering onlyhour
andminute
let dateArray = times.map { Calendar.current.dateComponents([.hour, .minute], from:formatter.date(from:$0)!) }
Map this array to the next date from now matching the components respectively
let upcomingDates = dateArray.map { Calendar.current.nextDate(after: Date(), matching: $0, matchingPolicy: .nextTime)! }
Sort the array ascending, the first item is the date you are looking for
let nextDate = upcomingDates.sorted().first!
Use the formatter to convert the date back to a time string
print(formatter.string(from:nextDate))
Swift 3 - Comparing Date objects
I have tried this snippet (in Xcode 8 Beta 6), and it is working fine.
let date1 = Date()
let date2 = Date().addingTimeInterval(100)
if date1 == date2 { ... }
else if date1 > date2 { ... }
else if date1 < date2 { ... }
Compare only time difference in Date objects
You can use Calendar
to extract the DateComponents
and then combine the day, month, and year from one with the hour, minute, and second of the other into another Date
object. Then you can compare the two Date
objects that share the same date using the well documented methods.
For example, given date1
and date2
, we can calculate date3
with date of date1
, but time of date2
. We can then compare date1
to this new date3
:
let calendar = Calendar.current
let components2 = calendar.dateComponents([.hour, .minute, .second], from: date2)
let date3 = calendar.date(bySettingHour: components2.hour!, minute: components2.minute!, second: components2.second!, of: date1)!
Then, to get the number of minutes between date1
and date3
:
let minutes = calendar.dateComponents([.minute], from: date1, to: date3).minute!
Or hours and minutes:
let difference = calendar.dateComponents([.hour, .minute], from: date1, to: date3)
let hours = difference.hour!
let minutes = difference.minute!
Or, if you want to show this to the user, you'd often use DateComponentsFormatter
to get a nice, localized string representation:
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [.hour, .minute] // or [.minute]
let string = formatter.string(from: date1, to: date3)!
Comparing NSDates without time component
Use this Calendar
function to compare dates in iOS 8.0+
func compare(_ date1: Date, to date2: Date, toGranularity component: Calendar.Component) -> ComparisonResult
passing .day
as the unit
Use this function as follows:
let now = Date()
// "Sep 23, 2015, 10:26 AM"
let olderDate = Date(timeIntervalSinceNow: -10000)
// "Sep 23, 2015, 7:40 AM"
var order = Calendar.current.compare(now, to: olderDate, toGranularity: .hour)
switch order {
case .orderedDescending:
print("DESCENDING")
case .orderedAscending:
print("ASCENDING")
case .orderedSame:
print("SAME")
}
// Compare to hour: DESCENDING
var order = Calendar.current.compare(now, to: olderDate, toGranularity: .day)
switch order {
case .orderedDescending:
print("DESCENDING")
case .orderedAscending:
print("ASCENDING")
case .orderedSame:
print("SAME")
}
// Compare to day: SAME
How can i compare two dates (NSDate) in Swift 3 and get the days between them?
Simply make extension of Date
like this and get difference in days.
extension Date {
func daysBetweenDate(toDate: Date) -> Int {
let components = Calendar.current.dateComponents([.day], from: self, to: toDate)
return components.day ?? 0
}
}
Now use this extension like this
let numOfDays = fromDate.daysBetweenDate(toDate: toDate)
You can use DateFormatter
to convert String to Date like this.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
let date = dateFormatter.date(from: "18-11-2016")
Get time difference between two times in swift 3
The recommended way to do any date math is Calendar
and DateComponents
let difference = Calendar.current.dateComponents([.hour, .minute], from: time1, to: time2)
let formattedString = String(format: "%02ld%02ld", difference.hour!, difference.minute!)
print(formattedString)
The format %02ld
adds the padding zero.
If you need a standard format with a colon between hours and minutes DateComponentsFormatter()
could be a more convenient way
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
print(formatter.string(from: time1, to: time2)!)
Need simple way to compare a time string ONLY to the current dates time value
the approach would be lets date the Date()
object from your current time object so you will get
default date + your time =
2000-01-01 00:00:00
+your time (7.00 AM or 9.00 PM)
now we will get the current time from today only, in same format. (Only time)
it will be something like
3.56 PM
now again we will convert this 3.56 PM
to Date()
with default date as prev. so now we will have two date time object with same Date(2000-01-01) and respective times.
- 2000-01-01 7:00:00 => this will your 7.00 AM with default date
- 2000-01-01 15:56:00 => this will be current time with default date
now we will compare two date object.
Check the fiddle Fiddle
func CompareMyTimeInString(myTime:String)->Bool
{
// create the formatter - we are expecting only "hh:mm a" format
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
dateFormatter.locale = Locale.init(identifier: "en_GB")
// default date with my time
var dt_MyTime = dateFormatter.date(from: yourTime)!
// current time in same format as string "hh:mm a"
var currentTimString = dateFormatter.string(from: Date());
print("Current Time is - "+currentTimString);
// current time with default date.
var dt_CurrentTime = dateFormatter.date(from: currentTimString)!
// now just compare two date objects :)
return dt_MyTime > dt_CurrentTime;
}
// then call it like
var yourTime = "7.00 AM"
var isDue = CompareMyTimeInString(myTime:yourTime);
print(isDue);
How to convert string to date without time in Swift 3?
let dateWithTime = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
let date = dateFormatter.string(from: dateWithTime) // 2/10/17
This will format it correctly, but this will be for display purposes only. All Date
s have time.
Comparing Time in ios Swift
Compare the time by ignoring the date component -
func checkTime() -> Bool {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "PKT")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let startingSlot = "2000-01-01 08:00:00" //UTC
let endingSlot = "2000-01-01 23:00:00" //UTC
let date = Date()
let date1: Date = dateFormatter.date(from: startingSlot)!
let date2: Date = dateFormatter.date(from: endingSlot)!
let currentTime = 60*Calendar.current.component(.hour, from: date) + Calendar.current.component(.minute, from: date) + (Calendar.current.component(.second, from: date)/60) // in minutes
let time1 = 60*Calendar.current.component(.hour, from: date1) + Calendar.current.component(.minute, from: date1) + (Calendar.current.component(.second, from: date1)/60) // in minutes
let time2 = 60*Calendar.current.component(.hour, from: date2) + Calendar.current.component(.minute, from: date2) + (Calendar.current.component(.second, from: date1)/60) // in minutes
print(currentTime)
print(time1)
print(time2)
if(currentTime >= time1 && currentTime <= time2) {
return true
} else {
return false
}
}
Output-
1121
510
1410
true
Related Topics
Trouble Passing Array Through Prepareforsegue
How to Use Protocols for Stucts to Emulate Classes Inheritance
Showing Action Sheet in The Custom Cell in Swift
Higlight Speech Utterance in Swiftui
Swift Custom Response Serializer Is Returning Images at Random
How to Get Data to Return from Nsurlsessiondatatask in Swift
Auto Height Does Not Work in UIview in Swift 3
Alamofire Nonblocking Connection
Retrieve Data from an Unknown Child Name with Firebase and Swift
Get Out of Navigation Controller and Go Back to Tab Bar View
Use The Same View for Adding and Editing Coredata Objects
Implementing a Custom Viewmodifier Where Output Is Conditional on Concrete View Type (Swiftui)
Encode Struct and Convert to Dictionary [String: Any]
Realitykit - Updating Entity's Translation Returns Unexpected Values
Pfuser That Created Object Cannot Delete Object Despite Acl Writing Access