Is there a date only (no time) class in Swift? (or Foundation classes)
There is no date only class that's part of the Foundation framework.
This is a quick way to get a date only representation of an NSDate object:
let now = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
print(dateFormatter.stringFromDate(now)) // Mar 3, 2016
NSDate's always have times because a date is a single point in time. If you're so inclined you can create a date without a time component but it usually defaults to 12AM:
let dateString = "2016-03-03"
let dateFromStringFormatter = NSDateFormatter()
dateFromStringFormatter.dateFormat = "yyyy-MM-dd"
let dateFromString = dateFromStringFormatter.dateFromString(dateString)
// dateFromString shows "Mar 3, 2016, 12:00 AM"
For Swift 3.0+
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
// optional
let date = dateFormatter.date(from: "2016-03-03") // Mar 3, 2015 at 12:00 AM
There isn't a date only class in Foundation
, but you can strip the time off from a Date
object, by using Calendar. In Swift 4:
func stripTime(from originalDate: Date) -> Date {
let components = Calendar.current.dateComponents([.year, .month, .day], from: originalDate)
let date = Calendar.current.date(from: components)
return date!
}
Or as an extension:
extension Date {
func stripTime() -> Date {
let components = Calendar.current.dateComponents([.year, .month, .day], from: self)
let date = Calendar.current.date(from: components)
return date!
}
}