0

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?

Wahib
  • 93
  • 1
  • 8
  • The best solution is to always use the same time for instance by doing `let startOfDay = Calendar.current.startOfDay(for: day)` – Joakim Danielson Sep 03 '20 at 10:57
  • but it creates a time with not 00 in the hours ! and a need that the date has eveything at zero except day month and year – Wahib Sep 03 '20 at 11:00
  • That's because of the time zone, the important part is that all dates get the same time. – Joakim Danielson Sep 03 '20 at 11:15
  • @Wahib for a time insensitive date you should use noon instead of midnight. Not all dates starts at 12am https://stackoverflow.com/questions/44009804/swift-3-how-to-get-date-for-tomorrow-and-yesterday-take-care-special-case-ne/44009988#44009988 – Leo Dabus Sep 03 '20 at 14:09

1 Answers1

0

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.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • i agree with you about the same moment in time. But my function needs to use other dates than only today, so i can't use your proposition – Wahib Sep 03 '20 at 11:05
  • `startOfDay(for:` returns the correct value for any date, even for a locale where the daylight saving time changes at midnight. – vadian Sep 03 '20 at 11:07