Reputation: 214
I want to get the only date in iOS and not time my code is
extension Date{
var DateInDate: Date{
let formatter = DateFormatter()
formatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd")
formatter.locale = Locale(identifier: "en_IN")
let dateInString = formatter.string(from: self)
return formatter.date(from: dateInString)!
}
}
if I am doing by the above format I am getting the answer as "Apr 3, 2019 at 12: 00 AM"
my other code is
extension Date{
var DateInDate: String{
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .none
formatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd")
formatter.locale = Locale(identifier: "en_IN")
let dateInString = formatter.string(from: self)
}
}
but in this way, I am getting in string format and not a Date format
I want the answer in date format
Upvotes: 0
Views: 583
Reputation: 519
Try this:
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.none
dateFormatter.dateStyle = DateFormatter.Style.short
dateFormatter.string(from: date)
Upvotes: 0
Reputation: 285064
As mentioned in the comments a Date
instance without the time portion is impossible.
In terms of Date
a timeless date is midnight, the start of the day.
There is an convenience API in Calendar
:
let startOfDay = Calendar.current.startOfDay(for: Date())
Upvotes: 1
Reputation: 46
You should use DateComponents instead. Date would always have the time.
Upvotes: 0