Truncate NSDate (Time Zero)

I want to create a new NSDate with 0 hours , 0 minutes and 0 seconds for time. The source date can be any random NSDate .

Is there any way to achieve this? The documentation didn't help me.




Example

There is: 2010-10-30 10:14:13 GMT

Want: 2010-10-30 00:00:00 GMT

+29
objective-c nsdate truncate
Nov 15 '10 at 18:11
source share
6 answers
 unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay; NSCalendar* calendar = [NSCalendar currentCalendar]; NSDateComponents* components = [calendar components:flags fromDate:date]; NSDate* dateOnly = [calendar dateFromComponents:components]; 

date - the date on which you want to delete the time.

Separates the date and time and creates a new date with the default time (00:00:00).

EDIT

To take into account the time zone:

 NSDate* dateOnly = [[calendar dateFromComponents:components] dateByAddingTimeInterval:[[NSTimeZone localTimeZone]secondsFromGMT]]; 
+63
Nov 15 '10 at 18:24
source share

Use NSCalendar rangeOfUnit:startDate:interval:forDate: This code will select the border of the day based on the current time zone. If you need a specific time zone, you need to create an NSCalendar and set its time zone accordingly.

 - (NSDate*)boundaryForCalendarUnit:(NSCalendarUnit)calendarUnit { NSDate *boundary; [[NSCalendar currentCalendar] rangeOfUnit:calendarUnit startDate:&boundary interval:NULL forDate:self]; return boundary; } - (NSDate*)dayBoundary { return [self boundaryForCalendarUnit:NSDayCalendarUnit]; } 
+16
Nov 15 '10 at 18:25
source share

With Swift 3, you can choose one of the following four templates to solve your problem.




# 1. Using Calendar startOfDay(for:)

startOfDay(for:) has the following declaration:

 func startOfDay(for date: Date) -> Date 

Returns the first moment of the given Date , as Date .

The following is an example of a playground code:

 import Foundation let date = Date() // Get new date let calendar = Calendar.current let newDate = calendar.startOfDay(for: date) // Format dates let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_UK") dateFormatter.dateStyle = .short dateFormatter.timeStyle = .long let formattedDate = dateFormatter.string(from: date) let formattedNewDate = dateFormatter.string(from: newDate) // Print formatted dates print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST 



# 2. Using Calendar date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:)

date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:) has the following declaration:

 func date(bySettingHour hour: Int, minute: Int, second: Int, of date: Date, matchingPolicy: Calendar.MatchingPolicy = default, repeatedTimePolicy: Calendar.RepeatedTimePolicy = default, direction: Calendar.SearchDirection = default) -> Date? 

Returns a new Date representing the date calculated by setting the hour, minute, and second to the specified time with the specified Date .

The following is an example of a playground code:

 import Foundation let date = Date() // Get new date let calendar = Calendar.current let newDate = calendar.date(bySettingHour: 0, minute: 0, second: 0, of: date) // Format dates let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_UK") dateFormatter.dateStyle = .short dateFormatter.timeStyle = .long let formattedDate = dateFormatter.string(from: date) let formattedNewDate = dateFormatter.string(from: newDate!) // Print formatted dates print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST 



# 3. Using the Calendar methods dateComponents(_:from:) and date(from:)

dateComponents(_:from:) has the following declaration:

 func dateComponents(_ components: Set<Calendar.Component>, from date: Date) -> DateComponents 

Returns all components of a date date using the calendar time zone.

date(from:) has the following declaration:

 func date(from components: DateComponents) -> Date? 

Returns the date created from the specified components.

The following is an example code on a playground:

 import Foundation let date = Date() // Get new date let calendar = Calendar.current let components = calendar.dateComponents([.day, .month, .year], from: date) let newDate = calendar.date(from: components) // Format dates let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_UK") dateFormatter.dateStyle = .short dateFormatter.timeStyle = .long let formattedDate = dateFormatter.string(from: date) let formattedNewDate = dateFormatter.string(from: newDate!) // Print formatted dates print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST 



# 4. Using NSCalendar range(of:start:interval:for:)

range(of:start:interval:for:) has the following declaration:

 func range(of unit: NSCalendar.Unit, start datep: AutoreleasingUnsafeMutablePointer<NSDate?>?, interval tip: UnsafeMutablePointer<TimeInterval>?, for date: Date) -> Bool 

Returns by reference the start time and duration of this calendar block, which contains the specified date.

The following is an example of a playground code:

 import Foundation let date = Date() // Get new date let calendar = Calendar.current as NSCalendar var newDate: NSDate? calendar.range(of: .day, start: &newDate, interval: nil, for: date) // Format dates let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_UK") dateFormatter.dateStyle = .short dateFormatter.timeStyle = .long let formattedDate = dateFormatter.string(from: date) let formattedNewDate = dateFormatter.string(from: newDate as! Date) // Print formatted dates print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST 
+3
Mar 30 '17 at 14:56
source share

Swift 3

 extension Date { func trimTime() -> Date { var boundary = Date() var interval: TimeInterval = 0 _ = Calendar.current.dateInterval(of: .day, start: &boundary, interval: &interval, for: self) return Date(timeInterval: TimeInterval(NSTimeZone.system.secondsFromGMT()), since: boundary) } } 
+1
Oct 07 '16 at 16:21
source share

I know it late, but now there are better methods: why you just don’t use

Swift 2

 NSCalendar.currentCalendar().dateBySettingHour(0, minute: 0, second: 0, ofDate: yourDateToZeroOutTime, options: []) 

Swift 3 will be something without the NS prefix;)

+1
Nov 10 '16 at 15:04
source share

I would use the description method to get the given date as a string, and then change the string and create a new date using initWithString.

initWithString: Returns an NSDate object initialized with the date and time value specified by this string in the international string representation format.

  • (id) initWithString: (NSString *) description parameters description A string that indicates the date and time value in the international string representation format: YYYY-MM-DD HH: MM: SS Β± HHMM, where Β± HHMM is the time zone offset in hours and minutes GMT (e.g., "2001-03-24 10:45:32 +0600"). You must specify all the fields in the format string, including the time zone offset, which must have a plus or minus sign prefix. Return Value An NSDate object initialized with the date and time value specified by aString.
0
Nov 15 '10 at 18:24
source share



All Articles