Error Creating Simple Countdown to Date App in Swift 4 - swift

So, I am currently working on an app that will do a simple countdown to a specific date; however, I am getting this error: "Value of type '(NSCalendar.Unit, Date, Date [NSCalendar.Options]) -> ()' has no member 'day' "
Any way to fix this to finish the app?
class ViewController: UIViewController {
#IBOutlet weak var CountdownText: UILabel!
let formatter = DateFormatter()
let userCalendar = NSCalendar.current
let requestedComponent: NSCalendar.Unit = [
NSCalendar.Unit.month,
NSCalendar.Unit.day,
NSCalendar.Unit.hour,
NSCalendar.Unit.minute,
NSCalendar.Unit.second,
]
func printTime()
{
formatter.dateFormat = "MM/dd/yy hh:mm:ss a"
let startTime = NSDate()
let endTime = formatter.date(from: "12/03/18 2:00:00 p")
func timeDifference (requestedComponent: NSCalendar.Unit, from: Date, to: Date, options: [NSCalendar.Options]) {}
CountdownText.text = "\(timeDifference.day) Days \(timeDifference.minute) Minutes \(timeDifference.second) Seconds"
}
}

You're trying to get call .day property from your function type which does and returns nothing.
I bet your function timeDifference should be somewhere outside the printTime function.
Believe you want to do something like following:
func printTime() {
formatter.dateFormat = "MM/dd/yy hh:mm:ss a"
let startTime = Date()
let endTime = formatter.date(from: "12/03/18 2:00:00 p")
let days = timeDifference(requestedComponent: .day, from: startTime, to: endTime, options: [])
let minutes = timeDifference(requestedComponent: .minute, from: startTime, to: endTime, options: [])
let seconds = timeDifference(requestedComponent: .second, from: startTime, to: endTime, options: [])
CountdownText.text = "\(days) Days \(minutes) Minutes \(seconds) Seconds"
}
func timeDifference (requestedComponent: NSCalendar.Unit, from: Date, to: Date, options: [NSCalendar.Options]) -> Int {
var calculatedValue = 0
// calculatings
return calculatedValue
}

You've declared a function named timeDifference() and you're trying to access it like a variable instance
Here's what you need to do:-
func timeDifference (requestedComponent: NSCalendar.Unit, from: Date, to: Date, options: [NSCalendar.Options]) {
//Do your things here
}
And call the function inside the variable this way:-
var text = "\(timeDifference(requestedComponent: .day, from: Date(), to: Date(), options: [.searchBackwards])) Days \(timeDifference(requestedComponent: .minute, from: Date(), to: Date(), options: [.searchBackwards])) Minutes \(timeDifference(requestedComponent: .second, from: Date(), to: Date(), options: [.searchBackwards])) Seconds"
Additionally, you can make your function parameters optional like this:-
func timeDifference (requestedComponent: NSCalendar.Unit, from: Date, to: Date, options: [NSCalendar.Options]? = nil) {}
The fourth parameter here is optional and the you don't have to provide an option every time. It's considered to be nil without input and it won't affect you in any way, unless you use it somewhere within the function, where you might have to handle it with an 'if' statement
(Just in case if it helps!)
NOTE:-
You can also return a "NSCalendar.Unit" from your function and use it for calculation, in which case, your usage pattern is right.
But I assume that the function here is written for the purpose of calculation and you're dealing with a label's value to display the calculated result. Dealing this all within a function is the sole purpose of a function, and hence I recommend doing this

You are trying to use function (with no return type) as NSCalendarComponent, hence it is showing you error. Instead, you and get start time and end time components like this:
func printTime(){
formatter.dateFormat = "MM/dd/yy hh:mm:ss a"
let calendar = Calendar.current
let startTime=calendar.dateComponents([.hour,.minute,.second], from: Date())
print("\(startTime.hour!):\(startTime.minute!):\(startTime.second!)")
let endTime = calendar.dateComponents([.hour,.minute,.second], from: formatter.date(from: "12/03/18 2:00:00 p") ?? Date())
print("\(endTime.hour!):\(endTime.minute!):\(endTime.second!)")
//do calculations here for time difference
}
and now you can calculate time difference and show it on countdown text.

First of all don't use NSCalendar and NSDate at all in Swift 3+.
Your code doesn't work because the function timeDifference has no return value and does nothing anyway.
You probably mean
let requestedComponents: Set<Calendar.Component> = [.month, .day, .hour, .minute, .second]
...
func timeDifference (requestedComponents: Set<Calendar.Component>, from: Date, to: Date) -> DateComponents {
return Calendar.current.dateComponents(requestedComponents, from: from, to: to)
}
...
let difference = timeDifference(requestedComponents: requestedComponents, from: startTime, to: endTime)
CountdownText.text = "\(difference.day!) Days \(difference.minute!) Minutes \(difference.second!) Seconds"
There is a more convenient way to calculate and display time differences, DateComponentsFormatter
func printTime()
{
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yy hh:mm:ss a"
let startTime = Date()
let endTime = formatter.date(from: "12/03/18 2:00:00 p")!
let componentsFormatter = DateComponentsFormatter()
componentsFormatter.allowedUnits = [.hour, .minute, .second]
componentsFormatter.unitsStyle = .full
CountdownText.text = componentsFormatter.string(from: startTime, to: endTime)
}

Related

How do I compare two Date objects by hours, minutes and seconds; ignoring the dates? [duplicate]

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
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:
class Time: Comparable, Equatable {
init(_ date: Date) {
//get the current calender
let calendar = Calendar.current
//get just the minute and the hour of the day passed to it
let dateComponents = calendar.dateComponents([.hour, .minute], from: date)
//calculate the seconds since the beggining of the day for comparisions
let dateSeconds = dateComponents.hour! * 3600 + dateComponents.minute! * 60
//set the varibles
secondsSinceBeginningOfDay = dateSeconds
hour = dateComponents.hour!
minute = dateComponents.minute!
}
init(_ hour: Int, _ minute: Int) {
//calculate the seconds since the beggining of the day for comparisions
let dateSeconds = hour * 3600 + minute * 60
//set the varibles
secondsSinceBeginningOfDay = dateSeconds
self.hour = hour
self.minute = minute
}
var hour : Int
var minute: Int
var date: Date {
//get the current calender
let calendar = Calendar.current
//create a new date components.
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
return calendar.date(byAdding: dateComponents, to: Date())!
}
/// the number or seconds since the beggining of the day, this is used for comparisions
private let secondsSinceBeginningOfDay: Int
//comparisions so you can compare times
static func == (lhs: Time, rhs: Time) -> Bool {
return lhs.secondsSinceBeginningOfDay == rhs.secondsSinceBeginningOfDay
}
static func < (lhs: Time, rhs: Time) -> Bool {
return lhs.secondsSinceBeginningOfDay < rhs.secondsSinceBeginningOfDay
}
static func <= (lhs: Time, rhs: Time) -> Bool {
return lhs.secondsSinceBeginningOfDay <= rhs.secondsSinceBeginningOfDay
}
static func >= (lhs: Time, rhs: Time) -> Bool {
return lhs.secondsSinceBeginningOfDay >= rhs.secondsSinceBeginningOfDay
}
static func > (lhs: Time, rhs: Time) -> Bool {
return lhs.secondsSinceBeginningOfDay > rhs.secondsSinceBeginningOfDay
}
}
Date Extension for easy access:
//Adds ability to just get the time from a date:
extension Date {
var time: Time {
return Time(self)
}
}
Example:
let firstDate = Date()
let secondDate = firstDate
//Will return true
let timeEqual = firstDate.time == secondDate.time
Much simpler than accepted answer:
SWIFT 4
// date1 and date2 are the dates you want to compare
let calendar = Calendar.current
var newDate = Date(TimeIntervalSinceReferenceDate: 0) // Initiates date at 2001-01-01 00:00:00 +0000
var newDate1 = Date(TimeIntervalSinceReferenceDate: 0) // Same as above
// Recieving the components from the dates you want to compare
let newDateComponents = calendar.dateComponents([.hour, .minute], from: date1)!
let newDate1Components = calendar.dateComponents([.hour, .minute], from: date2)!
// Adding those components
newDate = calendar.date(byAdding: newDateComponents, to: newDate)
newDate1 = calendar.date(byAdding: newDate1Components, to: newDate1)
My approach would be to use Calendar to make them Date objects with the same day and then comparing them using for example timeIntervalSinceReferenceDate.
Another, cleaner (but most likely with more lines of resulting code) would be to create extension for Date called secondsFromBeginningOfTheDay() -> TimeInterval and then comparing the resulting double values.
Example based on the second approach:
// Creating Date from String
let textDate1 = "2017-01-13T12:21:00-0800"
let textDate2 = "2016-03-06T20:12:05-0900"
let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZ"
formatter.timeZone = TimeZone.current
return formatter
} ()
// Dates used for the comparison
let date1 = dateFormatter.date(from: textDate1)
let date2 = dateFormatter.date(from: textDate2)
// Date extensions
extension Date {
func secondsFromBeginningOfTheDay() -> TimeInterval {
let calendar = Calendar.current
// omitting fractions of seconds for simplicity
let dateComponents = calendar.dateComponents([.hour, .minute, .second], from: self)
let dateSeconds = dateComponents.hour! * 3600 + dateComponents.minute! * 60 + dateComponents.second!
return TimeInterval(dateSeconds)
}
// Interval between two times of the day in seconds
func timeOfDayInterval(toDate date: Date) -> TimeInterval {
let date1Seconds = self.secondsFromBeginningOfTheDay()
let date2Seconds = date.secondsFromBeginningOfTheDay()
return date2Seconds - date1Seconds
}
}
if let date1 = date1, let date2 = date2 {
let diff = date1.timeOfDayInterval(toDate: date2)
// as text
if diff > 0 {
print("Time of the day in the second date is greater")
} else if diff < 0 {
print("Time of the day in the first date is greater")
} else {
print("Times of the day in both dates are equal")
}
// show interval as as H M S
let timeIntervalFormatter = DateComponentsFormatter()
timeIntervalFormatter.unitsStyle = .abbreviated
timeIntervalFormatter.allowedUnits = [.hour, .minute, .second]
print("Difference between times since midnight is", timeIntervalFormatter.string(from: diff) ?? "n/a")
}
// Output:
// Time of the day in the second date is greater
// Difference between times since midnight is 8h 51m 5s
My solution for comparing two times of day while ignoring the date:
let date1 = some time as a date
let date2 = some other time as a date
let time1 = 60*Calendar.current.component(.hour, from: date1!) + Calendar.current.component(.minute, from: date1!)
let time2 = 60*Calendar.current.component(.hour, from: date2!) + Calendar.current.component(.minute, from: date2!)
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.
This code works, check it easily in playground
let s1 = "22:31"
let s2 = "14:31"
let f = DateFormatter()
f.dateFormat = "HH:mm"
f.date(from: s1)! //"Jan 1, 2000 at 10:31 PM"
f.date(from: s2)! //"Jan 1, 2000 at 2:31 PM"
f.date(from: s1)! > f.date(from: s2)! // true
There's no standard type for a time-of-day. A reasonable type to start with is just a tuple:
typealias TimeOfDay = (hour: Int, minute: Int, second: Int)
To create these TimeOfDay values, you'll need a Calendar. By default, a Calendar uses the device's system-wide time zone. If you don't want that, set the Calendar's time zone explicitly. Example:
var calendar = Calendar.autoupdatingCurrent
calendar.timeZone = TimeZone(abbreviation: "UTC")!
Now you can use a DateFormatter to convert strings to Dates (if necessary), and then use calendar to extract the time-of-day components from the Dates:
let strings: [String] = ["2017-01-13 11:40:17 +0000", "2016-03-15 10:22:14 +0000"]
let parser = DateFormatter()
parser.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let timesOfDay: [TimeOfDay] = strings.map({ (string) -> TimeOfDay in
let components = calendar.dateComponents([.hour, .minute, .second], from: parser.date(from: string)!)
return (hour: components.hour!, minute: components.minute!, second: components.second!)
})
Swift.print(timesOfDay)
// Output: [(11, 40, 17), (10, 22, 14)]
Finally, you can compare these TimeOfDay values. Swift comes with standard comparison operators for tuples whose elements are Comparable, so this TimeOfDay type qualifies. You can just say this:
if timesOfDay[0] < timesOfDay[1] {
Swift.print("date[0] comes first")
} else if timesOfDay[0] == timesOfDay[1] {
Swift.print("times are equal")
} else {
Swift.print("date[1] comes first")
}
Let say we got two dates in string format:
// "2017-01-13 11:40:17 +0000"
// "2016-03-15 10:22:14 +0000"
We need to convert this strings to Date format, we create DateFormatter() and set the format ("yyyy-MM-dd' 'HH:mm:ssZ") it gonna convert
//date formatter converts string to date in our case
let firstDateFormatter = DateFormatter()
firstDateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ssZ"
Now we can get our date from string to Date format
//convert string to dates
if let date1 = firstDateFormatter.date(from: "2017-01-13 09:40:17 +0000"),
let date2 = firstDateFormatter.date(from: "2016-03-15 10:22:14 +0000") {
What we want is to compare only Hours and Minutes. So change dateformat to "HH:mm"
//we ve got the dates, now switch dateformat for other job
firstDateFormatter.dateFormat = "HH:mm"
Now get the string value from our date, that only contain "HH:mm"
// convert date to string ( part of string we want to compare )
let HHmmDate1 = firstDateFormatter.string(from: date1) //"17:40"
let HHmmDate2 = firstDateFormatter.string(from: date2) //"18:22"
Final step is to get date from our "HH:mm" values, let say we ask DateFormatter to give us a date, based on time only, in our case "17:40" and "18:22". DateFormatter will put some values for dates, so we get Jan 1, 2000 automatically for both dates, but it will get the time we provide.
//produce "default" dates with desired HH:mm
//default means same date, but time is different
let HH1 = firstDateFormatter.date(from: HHmmDate1) //"Jan 1, 2000 at 5:40 PM"
let HH2 = firstDateFormatter.date(from: HHmmDate2) //"Jan 1, 2000 at 6:22 PM"
Now we could easily compare dates
//compare
HH1! > HH2!
}
There are many options to compare dates with Calendar also
This is very simple in Swift if you use Swifter Swift
date1.day = 1
date1.month = 1
date1.year = 2000
date2.day = 1
date2.month = 1
date2.year = 2000
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.
public var day: Int {
get {
return Calendar.current.component(.day, from: self)
}
set {
let allowedRange = Calendar.current.range(of: .day, in: .month, for: self)!
guard allowedRange.contains(newValue) else { return }
let currentDay = Calendar.current.component(.day, from: self)
let daysToAdd = newValue - currentDay
if let date = Calendar.current.date(byAdding: .day, value: daysToAdd, to: self) {
self = date
}
}
}

Get All Hours of The Day (in date format) from 9am tp 11pm and Save within an array in Swift

I need to get all the remaining hours of the day starting from whatever the current hour is until 11pm and save it in an array in a date format. Here is what I have written so far:
var sortedTime: [Date] = {
let today = Date()
var sortedTime: [Date] = []
(0..<14).forEach {
sortedTime.append(Calendar.current.date(byAdding: .hour, value: $0, to: today)!)
}
return sortedTime
}()
In the code I have: (0..<14).forEach { This is giving me the next 14 hours but thats not what I need; I need to make sure the hours I get are between 9am and 11pm. How would I be able to set this limit?
When you access .hour for any calender its in a 24h format. so you need to something like this:
let today = Date()
var sortedTime: [Date] = []
var calender = Calendar(identifier: .iso8601)
calender.locale = Locale(identifier: "en_US_POSIX")
let currentHour = calender.component(.hour, from: today)
(0...(24-currentHour)).forEach {
guard let newDate = calender.date(byAdding: .hour, value: $0, to: today) && calender.component(.hour, from: newDate) != 0,
calender.component(.hour, from: newDate) <= 23 else {
return
}
//convert date into desired format
sortedTime.append(newDate)
}

Cannot convert value of type 'Date' to expected argument type 'Date'

In playgrounds this code works great and I get the expected output exactly as I want, but when I go put it in my Xcode project I get 3 warning with my startDate saying
Cannot convert value of type 'Date' to expected argument type 'Date'
Here is my code:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM, dd yyyy"
let date = dateFormatter.date(from: "June, 27 2018")
if let date = date {
let calendar = Calendar(identifier: .gregorian)
var startDate : Date = Date()
var interval : TimeInterval = 0
if calendar.dateInterval(of: .weekOfYear, start: &startDate, interval: &interval, for: date) {
print(startDate)
let daysToAdd = 6
var dateComponent = DateComponents()
dateComponent.day = daysToAdd
let futureDate = Calendar.current.date(byAdding: dateComponent, to: startDate)
let dateFormatter1 = DateFormatter()
dateFormatter1.dateFormat = "MMMM dd-"
let dateFormatter2 = DateFormatter()
let startWeek = dateFormatter1.string(from: startDate)
dateFormatter2.dateFormat = "dd"
let endWeek = dateFormatter2.string(from: futureDate!)
results = "\(startWeek)\(endWeek)"
}
}
The green text color on Date type in
var startDate : Date = Date()
means that you have your own class/struct that is called Date. That one cannot be converted to Foundation.Date.
It's not a good idea to create this kind of name conflict in the first place but you can fix it just using the full name:
var startDate = Foundation.Date()
var startDate = Date()
I had the same issue and I fixed that with the code above. hope works for you.
To illustrate this issue with an example.
This will produce the error, because while I did want to return a Date in the Result object, I didn't need to create a generic called Date at the interface for this function. That was my mistake.
func daysAgo<Date>(_ dayCount: Int) -> Result<Date, CommonErrors> {
let date: Date? = Calendar.current.date(byAdding: .day, value: dayCount, to: self)
return Result(success: date, failure: .initFailed)
}
The following code solves my issue:
func daysAgo(_ dayCount: Int) -> Result<Date, CommonErrors> {
let date: Date? = Calendar.current.date(byAdding: .day, value: dayCount, to: self)
return Result(success: date, failure: .initFailed)
}

Joining separated Date and Hour to create a single Date() Object

I have this app written in swift where I get a future date and a future hour (As Unix Timestamp) separately and I want to turned them into one Date() Object so I can converted to Unix Timestamp.
If you now another way to converted directly to Unix Timestamp feel free to post.
This may give you some ideas on how to accomplish what you want:
let calendar = Calendar.current
let currentDate = Date()
// Random future date, 1 month from now
let futureDate = calendar.date(byAdding: .month, value: 1, to: currentDate)!
let futureDateComponents = calendar.dateComponents([.year, .month, .day], from: futureDate)
// Random hour
let futureHour = 2
// Use your future date and your future hour to set the components for the new date to be created
var newDateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: currentDate)
newDateComponents.year = futureDateComponents.year
newDateComponents.month = futureDateComponents.month
newDateComponents.day = futureDateComponents.day
newDateComponents.hour = futureHour
newDateComponents.minute = 0
newDateComponents.second = 0
// Create a new date from components
let newDate = calendar.date(from: newDateComponents)!
// Convert new date to unix time format
let unixTime = newDate.timeIntervalSince1970
print(newDate) // 2018-03-06 02:00:00 +0000
print(unixTime) // 1520301600.0
Note that in a real project you should avoid force unwrapping (i.e. using '!').
If you have a date string in the form of dd-MM-yyyy, you can convert that to a Date object like so:
let string = "02-06-2018"
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
formatter.locale = Locale(identifier: "en_US_POSIX") // this is only needed if string is always gregorian but you don't know what locale the device is using
guard let date = formatter.date(from: string) else {
// handle error however you'd like
return
}
Or, if you already have a Date object, then you don't need the above. But regardless, once you have a Date, you can then get a Date by setting the hour, minute, and second as follows:
let hour = 14 // 2pm
guard let result = Calendar.current.date(bySettingHour: hour, minute: 0, second: 0, of: date) else {
// handle error however you'd like
return
}

How do you compare just the time of a Date in Swift?

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
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:
class Time: Comparable, Equatable {
init(_ date: Date) {
//get the current calender
let calendar = Calendar.current
//get just the minute and the hour of the day passed to it
let dateComponents = calendar.dateComponents([.hour, .minute], from: date)
//calculate the seconds since the beggining of the day for comparisions
let dateSeconds = dateComponents.hour! * 3600 + dateComponents.minute! * 60
//set the varibles
secondsSinceBeginningOfDay = dateSeconds
hour = dateComponents.hour!
minute = dateComponents.minute!
}
init(_ hour: Int, _ minute: Int) {
//calculate the seconds since the beggining of the day for comparisions
let dateSeconds = hour * 3600 + minute * 60
//set the varibles
secondsSinceBeginningOfDay = dateSeconds
self.hour = hour
self.minute = minute
}
var hour : Int
var minute: Int
var date: Date {
//get the current calender
let calendar = Calendar.current
//create a new date components.
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
return calendar.date(byAdding: dateComponents, to: Date())!
}
/// the number or seconds since the beggining of the day, this is used for comparisions
private let secondsSinceBeginningOfDay: Int
//comparisions so you can compare times
static func == (lhs: Time, rhs: Time) -> Bool {
return lhs.secondsSinceBeginningOfDay == rhs.secondsSinceBeginningOfDay
}
static func < (lhs: Time, rhs: Time) -> Bool {
return lhs.secondsSinceBeginningOfDay < rhs.secondsSinceBeginningOfDay
}
static func <= (lhs: Time, rhs: Time) -> Bool {
return lhs.secondsSinceBeginningOfDay <= rhs.secondsSinceBeginningOfDay
}
static func >= (lhs: Time, rhs: Time) -> Bool {
return lhs.secondsSinceBeginningOfDay >= rhs.secondsSinceBeginningOfDay
}
static func > (lhs: Time, rhs: Time) -> Bool {
return lhs.secondsSinceBeginningOfDay > rhs.secondsSinceBeginningOfDay
}
}
Date Extension for easy access:
//Adds ability to just get the time from a date:
extension Date {
var time: Time {
return Time(self)
}
}
Example:
let firstDate = Date()
let secondDate = firstDate
//Will return true
let timeEqual = firstDate.time == secondDate.time
Much simpler than accepted answer:
SWIFT 4
// date1 and date2 are the dates you want to compare
let calendar = Calendar.current
var newDate = Date(TimeIntervalSinceReferenceDate: 0) // Initiates date at 2001-01-01 00:00:00 +0000
var newDate1 = Date(TimeIntervalSinceReferenceDate: 0) // Same as above
// Recieving the components from the dates you want to compare
let newDateComponents = calendar.dateComponents([.hour, .minute], from: date1)!
let newDate1Components = calendar.dateComponents([.hour, .minute], from: date2)!
// Adding those components
newDate = calendar.date(byAdding: newDateComponents, to: newDate)
newDate1 = calendar.date(byAdding: newDate1Components, to: newDate1)
My approach would be to use Calendar to make them Date objects with the same day and then comparing them using for example timeIntervalSinceReferenceDate.
Another, cleaner (but most likely with more lines of resulting code) would be to create extension for Date called secondsFromBeginningOfTheDay() -> TimeInterval and then comparing the resulting double values.
Example based on the second approach:
// Creating Date from String
let textDate1 = "2017-01-13T12:21:00-0800"
let textDate2 = "2016-03-06T20:12:05-0900"
let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZ"
formatter.timeZone = TimeZone.current
return formatter
} ()
// Dates used for the comparison
let date1 = dateFormatter.date(from: textDate1)
let date2 = dateFormatter.date(from: textDate2)
// Date extensions
extension Date {
func secondsFromBeginningOfTheDay() -> TimeInterval {
let calendar = Calendar.current
// omitting fractions of seconds for simplicity
let dateComponents = calendar.dateComponents([.hour, .minute, .second], from: self)
let dateSeconds = dateComponents.hour! * 3600 + dateComponents.minute! * 60 + dateComponents.second!
return TimeInterval(dateSeconds)
}
// Interval between two times of the day in seconds
func timeOfDayInterval(toDate date: Date) -> TimeInterval {
let date1Seconds = self.secondsFromBeginningOfTheDay()
let date2Seconds = date.secondsFromBeginningOfTheDay()
return date2Seconds - date1Seconds
}
}
if let date1 = date1, let date2 = date2 {
let diff = date1.timeOfDayInterval(toDate: date2)
// as text
if diff > 0 {
print("Time of the day in the second date is greater")
} else if diff < 0 {
print("Time of the day in the first date is greater")
} else {
print("Times of the day in both dates are equal")
}
// show interval as as H M S
let timeIntervalFormatter = DateComponentsFormatter()
timeIntervalFormatter.unitsStyle = .abbreviated
timeIntervalFormatter.allowedUnits = [.hour, .minute, .second]
print("Difference between times since midnight is", timeIntervalFormatter.string(from: diff) ?? "n/a")
}
// Output:
// Time of the day in the second date is greater
// Difference between times since midnight is 8h 51m 5s
My solution for comparing two times of day while ignoring the date:
let date1 = some time as a date
let date2 = some other time as a date
let time1 = 60*Calendar.current.component(.hour, from: date1!) + Calendar.current.component(.minute, from: date1!)
let time2 = 60*Calendar.current.component(.hour, from: date2!) + Calendar.current.component(.minute, from: date2!)
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.
This code works, check it easily in playground
let s1 = "22:31"
let s2 = "14:31"
let f = DateFormatter()
f.dateFormat = "HH:mm"
f.date(from: s1)! //"Jan 1, 2000 at 10:31 PM"
f.date(from: s2)! //"Jan 1, 2000 at 2:31 PM"
f.date(from: s1)! > f.date(from: s2)! // true
There's no standard type for a time-of-day. A reasonable type to start with is just a tuple:
typealias TimeOfDay = (hour: Int, minute: Int, second: Int)
To create these TimeOfDay values, you'll need a Calendar. By default, a Calendar uses the device's system-wide time zone. If you don't want that, set the Calendar's time zone explicitly. Example:
var calendar = Calendar.autoupdatingCurrent
calendar.timeZone = TimeZone(abbreviation: "UTC")!
Now you can use a DateFormatter to convert strings to Dates (if necessary), and then use calendar to extract the time-of-day components from the Dates:
let strings: [String] = ["2017-01-13 11:40:17 +0000", "2016-03-15 10:22:14 +0000"]
let parser = DateFormatter()
parser.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let timesOfDay: [TimeOfDay] = strings.map({ (string) -> TimeOfDay in
let components = calendar.dateComponents([.hour, .minute, .second], from: parser.date(from: string)!)
return (hour: components.hour!, minute: components.minute!, second: components.second!)
})
Swift.print(timesOfDay)
// Output: [(11, 40, 17), (10, 22, 14)]
Finally, you can compare these TimeOfDay values. Swift comes with standard comparison operators for tuples whose elements are Comparable, so this TimeOfDay type qualifies. You can just say this:
if timesOfDay[0] < timesOfDay[1] {
Swift.print("date[0] comes first")
} else if timesOfDay[0] == timesOfDay[1] {
Swift.print("times are equal")
} else {
Swift.print("date[1] comes first")
}
Let say we got two dates in string format:
// "2017-01-13 11:40:17 +0000"
// "2016-03-15 10:22:14 +0000"
We need to convert this strings to Date format, we create DateFormatter() and set the format ("yyyy-MM-dd' 'HH:mm:ssZ") it gonna convert
//date formatter converts string to date in our case
let firstDateFormatter = DateFormatter()
firstDateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ssZ"
Now we can get our date from string to Date format
//convert string to dates
if let date1 = firstDateFormatter.date(from: "2017-01-13 09:40:17 +0000"),
let date2 = firstDateFormatter.date(from: "2016-03-15 10:22:14 +0000") {
What we want is to compare only Hours and Minutes. So change dateformat to "HH:mm"
//we ve got the dates, now switch dateformat for other job
firstDateFormatter.dateFormat = "HH:mm"
Now get the string value from our date, that only contain "HH:mm"
// convert date to string ( part of string we want to compare )
let HHmmDate1 = firstDateFormatter.string(from: date1) //"17:40"
let HHmmDate2 = firstDateFormatter.string(from: date2) //"18:22"
Final step is to get date from our "HH:mm" values, let say we ask DateFormatter to give us a date, based on time only, in our case "17:40" and "18:22". DateFormatter will put some values for dates, so we get Jan 1, 2000 automatically for both dates, but it will get the time we provide.
//produce "default" dates with desired HH:mm
//default means same date, but time is different
let HH1 = firstDateFormatter.date(from: HHmmDate1) //"Jan 1, 2000 at 5:40 PM"
let HH2 = firstDateFormatter.date(from: HHmmDate2) //"Jan 1, 2000 at 6:22 PM"
Now we could easily compare dates
//compare
HH1! > HH2!
}
There are many options to compare dates with Calendar also
This is very simple in Swift if you use Swifter Swift
date1.day = 1
date1.month = 1
date1.year = 2000
date2.day = 1
date2.month = 1
date2.year = 2000
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.
public var day: Int {
get {
return Calendar.current.component(.day, from: self)
}
set {
let allowedRange = Calendar.current.range(of: .day, in: .month, for: self)!
guard allowedRange.contains(newValue) else { return }
let currentDay = Calendar.current.component(.day, from: self)
let daysToAdd = newValue - currentDay
if let date = Calendar.current.date(byAdding: .day, value: daysToAdd, to: self) {
self = date
}
}
}