Returns a new date representing the date calculated by setting a specific component of a given date to a given value, while trying to keep lower components the same.
SDKs
- iOS 8.0+
- macOS 10.9+
- Mac Catalyst 13.0+
- tvOS 9.0+
- watchOS 2.0+
Framework
- Foundation
Declaration
- (NSDate *)dateBySettingUnit:(NSCalendar Unit)unit value:(NSInteger)v ofDate:(NSDate *)date options:(NSCalendar Options)opts;
Parameters
unit
The unit to set with the given value. For possible values, see
NSCalendar
.Unit v
The value to set for the given calendar unit.
date
The date to use to perform the calculation.
opts
Options for the calculation. For possible values, see
NSCalendar
.Options
Return Value
A new NSDate
instance representing the date calculated by setting a specific component of a given date to a given value. If the unit already has that value, this may result in a date which is the same as the given date. If no such time exists for the specified components, the next available date is returned, which may be on a different calendar day.
Discussion
Changing a component's value often requires higher or coupled components to change as well. For example, setting the weekday
to "Thursday" will require the day
component to change its value, and possibly the month
and year
as well. You can use the next
method to specify more precise behavior for determining the next or previous date for a given date component.