remove time from a date like this 2016-02-10 00:00:00
A better way than proposed versions is not to convert from date using a string formatter, but instead using calendar:
public func removeTimeStamp(fromDate: Date) -> Date {
guard let date = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day], from: fromDate)) else {
fatalError("Failed to strip time from Date object")
}
return date
}
okay I solved this myself
let date = "2016-02-10 00:00:00"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let dateFromString : NSDate = dateFormatter.dateFromString(date)!
dateFormatter.dateFormat = "dd-MM-yyyy"
let datenew= dateFormatter.stringFromDate(dateFromString)
print(datenew)
Using an extension on the Date:
extension Date {
public var removeTimeStamp : Date? {
guard let date = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day], from: self)) else {
return nil
}
return date
}
}
Usage:
let now = Date()
let nowWithouTime = now.removeTimeStamp