I have three date objects. I want to know, which of them is the oldest. I found a lot about how to compare two dates, but not multiple...
So I have my three date variables:
var firstDate:Date!
var secondDate:Date!
var thridDate:Date!
and I assign dates to them:
firstDaten = dateOne
secondDate = dateTwo
thridDate = dateThree
How can I find out in Swift, which of my dates is the oldest?
Tanks for help!
As Date conforms to Comparable, create an array and use the min() function
let dates = [firstDate, secondDate, thridDate]
let oldest = dates.min()
Note:
It is not necessary to declare a variable as implicit unwrapped optional if a value is assigned right after the declaration, this compiles:
let firstDate : Date
firstDate = dateOne
Related
I'm very new to swift.
How to set empty value for Date type in Swift to be used in declarations?
Like:
var string: String = "" for String type
var integer: Int = 0 for Int type.
Thank you.
From the documentation :
A Date value encapsulate a single point in time, independent of any
particular calendrical system or time zone. Date values represent a
time interval relative to an absolute reference date.
In other terms, a date is nothing but a TimeInterval, A.K.A a Double representing the number of seconds since a reference date. Then, an empty initializer for Date would be the one that returns a date 0 seconds away from that reference date. It all comes down to choosing the reference date :
Now : let date1 = Date()
Jan 1, 1970 at 12:00 AM : let date2 = Date(timeIntervalSince1970: 0)
Jan 1, 2001 at 12:00 AM : let date3 = Date(timeIntervalSinceReferenceDate: 0)
You can choose a certain date as a reference if it makes sense to you. Examples: Date.distantPast, Date.distantFuture, ...
Now, if you want a variable to have a certain type, but no value, then use optionals and set their values to nil:
var date4: Date? = nil
Later on, when you want to actually use the variable, just set it to a non-nil value:
date4 = Date(timeInterval: -3600, since: Date())
To use the actual value, you'll have to unwrap it using optional binding or the likes of it.
I'm trying to pass a date to a function in Kotlin. I don't want to have to type "08/30/2018" as a String and would instead prefer Date. I initially tried just 08/30/2018 but get a compiler stating an Integer was found for the input rather than Date.
var myDate = 1/1/2000
var newDate = 08/30/2018
fun setDate(value: Int){
myDate = value
}
setDate(newDate)
println(newDate) //0
println(myDate) //0
println(myDate.compareTo(newDate)) //0
Why does Kotlin accept 08/30/2018 as an int? Why is it stored correctly to another int variable but then print 0 when the value is retrieved?
How can I initialize a variable to a date like 1/1/2000 and then set another date later on? I haven't found anything about passing a date anywhere unless it is a String.
When you assign 8/30/2018 to a variable then the compiler recognizes it as integer division 8/30 which is 0 and then /2018 and the result is 0.
You could do it like val date = Date("1/1/2000") but this is now deprecated
You can use the Java 8 Date/Time API instead:
val date = LocalDate.of(2000, 1, 1)
you can find more here:
https://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html
I want to sort an array of times in ascending order from 00:00 -> 23:59 in Swift 4. My application doesn't have any reference to a calendar as its used to register alarm times with an external hardware clock as a very basic alarm that simply goes from 00:00 -> 23:59 then wraps.
Not sure if this is the best approach, but i've tried the following code based on Sort Objects in Array by date
but I can't get it to work with just time only. The (date) object fails to initialise. It doesn't like the (dateStyle) and (timeStyle) changes from the initial example. Code is below:
let testArray = ["23:59", "01:23", "18:23", "04:42", "00:00"]
var convertedArray: [Date] = []
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .short
for dat in testArray {
let date = dateFormatter.date(from: dat)
if let date = date {
convertedArray.append(date)
}
}
var ready = convertedArray.sorted(by: { $0.compare($1) == .orderedAscending })
print(ready)
When working the print function should print the sorted array in the following order:
[00:00, 01:23, 04:42, 18:23, 23:59]
Anyone got any ideas?
You don't need to convert the strings into dates. Just sort the strings as numbers.
let testArray = ["23:59", "01:23", "18:23", "04:42", "00:00"]
let sortedArray = testArray.sorted { $0.localizedStandardCompare($1) == .orderedAscending }
print(sortedArray)
Output:
["00:00", "01:23", "04:42", "18:23", "23:59"]
As it turns out, since each of your time strings are in a nice fixed format of HH:mm, you don't even need to use localizedStandardCompare. You get the desired results with:
let sortedArray = testArray.sorted()
This only works since you have only numbers and because the numbers are padded with leading zeros. If either of those cases weren't there you would need the first option.
This is a very simple question but it's been bugging me. According to Swift, it's not possible for values of different types to be added together (like String and Int), how's it possible that the following code works even though it adds type Date and type Int together?
let someDate = Date() + 2828282
On the documentation page for Date you can see
that there is a +
operator taking a Date and TimeInterval as operands:
Returns a date with a specified amount of time added to it.
static func +(lhs: Date, rhs: TimeInterval) -> Date
So you can add a TimeInterval (which is a type alias for Double)
to a Date, but not an Int. Your code compiles because 2828282
is a "number literal" and the compiler can infer the type from
the context as Double.
This would not compile:
let delta = 2828282 // an Int
let someDate = Date() + delta
// error: binary operator '+' cannot be applied to operands of type 'Date' and 'Int'
You would have to convert the Int to a TimeInterval/Double
let delta = 2828282 // an Int
let someDate = Date() + TimeInterval(delta)
or make delta a Double:
let delta = 2828282.0 // a Double
let someDate = Date() + delta
According to Swift, it's not possible for values of different types to be added together (like String and Int)
Unlike in many other languages, there is no automatic conversions between numeric types, a.k.a numeric promotions, and the majority of pre-defined numeric operators expect both operands to be of the same type.
However there is nothing in Swift to prevent operators being declared with different type operands, and your example Date() + 2828282 is one example where a pre-defined operator is defined with different operand types.
So the difference with Swift is that is lacks automatic numeric promotions, and that combinations such realVar + intVar are not pre-defined.
In many other languages the combination is not pre-defined either, but numeric promotions exist, so the example is compiled as realVar + real(intVar).
HTH
I've two NSDates, one stamped by the devise, and the other entered by the user. I'd like to see if there is a difference between the two, and researched the following code, but I get an error message that NSDate is not identical to NSTimeInterval.
let compareResult = recordDateTimeEntered!.compare(recordDateTimeEntered!)
let timeFromEnteredtoStampedDates = recordDateTimeStamped.timeIntervalSinceReferenceDate(recordDateTimeEntered) // error: NSDate -> _ is not identical to NSTimeInterval
To compare two dates for equality, you can use the == operator in Swift (or the isEqualToDate: method in Objective-C). You can alternatively check that the timeIntervalSinceDate: between two dates is less than an acceptable threshold, to determine if two dates are roughly equal.