Search code examples
swiftdateformatter

In Swift, how to delete hours in a Date object?


i need to use a dictionary of dates, and i need to delete all the information about a date except: day month year

i create this static function:

let day = Date() // it's an example
print(day)

func dateSimplificator(WithDate date: Date) -> Date {
    let formatterD = DateFormatter()
    formatterD.dateFormat = "dd MM yyyy"
    let dayString = formatterD.string(from: date)
    let reFormatterD = DateFormatter()
    reFormatterD.dateFormat = "dd MM yyyy"
    let dayFormatted = reFormatterD.date(from: dayString)!
    //print(dayFormatted)
    return dayFormatted
}

print(dateSimplificator(WithDate: day))

and when i print, i obtain: 2020-09-03 10:40:25 +0000 2020-09-02 23:00:00 +0000

it isn't what i want. I need somthing like this:

the date => 2020-09-03 10:40:25 +0000 and when i use the static function with the date, i have to obtain a new date like this : 2020-09-02 00:00:00 +0000

what should a change in my function?


Solution

  • First of all your method can be written without a date formatter

    func dateSimplificator(with date: Date) -> Date {
        return Calendar.current.startOfDay(for: date)
    }
    

    Second of all a date formatter considers the local time zone – which is clearly UTC+0100 in your case – but print shows dates in UTC. 2020-09-03 00:00:00 +0100 and 2020-09-02 23:00:00 +0000 is the same moment in time.