I have two Date Objects:
2017-01-13 11:40:17 +0000
2016-03-15 10:22:14 +0000
I need to compare just the time of these values and ignore the date
example: 12:00am and 12:01am, 12:01 is later so (12:01am > 12:00am) == true
I have two Date Objects:
2017-01-13 11:40:17 +0000
2016-03-15 10:22:14 +0000
I need to compare just the time of these values and ignore the date
example: 12:00am and 12:01am, 12:01 is later so (12:01am > 12:00am) == true
My approach would be to use
Calendar
to make themDate
objects with the same day and then comparing them using for exampletimeIntervalSinceReferenceDate
.Another, cleaner (but most likely with more lines of resulting code) would be to create extension for
Date
calledsecondsFromBeginningOfTheDay() -> TimeInterval
and then comparing the resulting double values.Example based on the second approach:
This is very simple in Swift if you use Swifter Swift
now you can use >,<,== operators on date1 and date2 to compare just the time components.
edit - you could do this your self by extending the date class, for example swifter-swift does the bellow for the day component.
This is the route I took in the end, which makes it easy to compare just the time of a Date in swift
New Object Time:
Date Extension for easy access: //Adds ability to just get the time from a date:
Example:
I had a problem doing just this and I think I found a simpler solution if you just want to compare the time of two dates. It does feel a little "hacky" but seems to work well.
SWIFT 4
My solution for comparing two times of day while ignoring the date:
Now you can compare the integers time1 and time2 without regard to the day. You could add the seconds/60 if you need more precision.
There's no standard type for a time-of-day. A reasonable type to start with is just a tuple:
To create these
TimeOfDay
values, you'll need aCalendar
. By default, aCalendar
uses the device's system-wide time zone. If you don't want that, set theCalendar
's time zone explicitly. Example:Now you can use a
DateFormatter
to convert strings toDate
s (if necessary), and then usecalendar
to extract the time-of-day components from theDate
s:Finally, you can compare these
TimeOfDay
values. Swift comes with standard comparison operators for tuples whose elements areComparable
, so thisTimeOfDay
type qualifies. You can just say this: