0

I've got a Date object that holds year/month/day and hour/minute/second data. I need to drop the hour/minute/second part as it's making comparing days problematic.

The issue is that the only obvious way I see of doing it is turning the day into a String and then using a DateFormatter with yyyy/mm/dd format to turn it BACK into a Date. This seems like a waste, is it really the only way?

Thanks a lot.

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
Return-1
  • 2,329
  • 3
  • 21
  • 56
  • A Date object does not hold year/month/day or hour/minute/second data, and a Date has no format. – A Date represents an absolute point in time, stored internally as the number of seconds since 00:00:00 UTC on 1 January 2001. – Martin R Oct 05 '17 at 14:31

1 Answers1

1

Never convert dates to String and back to Date.

You are looking for the startOfDay function of Calendar:

let date = Date()
let startOfDay = Calendar.current.startOfDay(for: date)
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223