I want to generate a new NSDate
with 0 hours, 0 minutes, and 0 seconds for time. The source date can be any random NSDate
.
Is there a way to achieve this? The documentation did not help me with this.
Example
Have: 2010-10-30 10:14:13 GMT
Want: 2010-10-30 00:00:00 GMT
I would use the description method to get the given date as a string, then modify the string and create your new date with initWithString.
initWithString: Returns an NSDate object initialized with a date and time value specified by a given string in the international string representation format.
With Swift 3, you can choose one of the four following patterns in order to solve your problem.
#1. Using
Calendar
startOfDay(for:)
startOfDay(for:)
has the following declaration:The Playground code below shows how to use this method:
#2. Using
Calendar
date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:)
date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:)
has the following declaration:The Playground code below shows how to use this method:
#3. Using
Calendar
dateComponents(_:from:)
anddate(from:)
methodsdateComponents(_:from:)
has the following declaration:date(from:)
has the following declaration:The Playground code below shows how to use those methods:
#4. Using
NSCalendar
range(of:start:interval:for:)
range(of:start:interval:for:)
has the following declaration:The Playground code below shows how to use this method:
date
is the date you want to remove the time from.This separates the date and time and creates a new date with the default time (00:00:00).
EDIT
To take time zone into account:
I know its late, but there are now better methods: why dont you just use
Swift 2
Swift 3 would be something without the NS prefix ;)
Swift 3
Use NSCalendar's
rangeOfUnit:startDate:interval:forDate:
. This code will choose the day boundary based on the current time zone. If you want a particular time zone, you need to create an NSCalendar and set its time zone appropriately.