Is there a date only (no time) class in Swift? (or Foundation classes)
(as an aside if there is not but there is a well known/popular open-source library that implements this if you could mention this)
EDIT: Updated to clarify with " (or Foundation classes)"
In Swift, a Date() value encapsulates a single point in time, independent of any particular time zone or calendarical system. To accomplish this, a Date() value is stored as a 64-bit floating point number counting the number of seconds as a relative offset from the reference date of January 1, 2001 at 00:00:00 UTC.
Swift – Get Current Time Only To get only current time, containing hour, minute and second, use Date and DateFormatter . Date returns current point in time, while DateFormatter with specified dateFormat formats this Date value to required format, like in this case returning only time (hour, minute and second).
The date format of the string that is passed to date(from:) method is MM/dd/yy while the dateFormat property has a value of dd/MM/yy .
If you want to get a Date object in Swift 4, like when you are trying to store a Date object in core data, you can use this method.
private func getDate() -> Date {
let today = Date()
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.none
dateFormatter .dateStyle = DateFormatter.Style.short
let dateAsString = dateFormatter.string(from: today)
return dateFormatter.date(from: dateAsString)!
}
based on @John R Perry's answer.
Swift 3.0
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.none
dateFormatter.dateStyle = DateFormatter.Style.short
dateFormatter.string(from: date) // 12/15/16
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With