Contents

NSDateComponents

An object that specifies a date or time in terms of units (such as year, month, day, hour, and minute) to be evaluated in a calendar system and time zone.

Declaration

class NSDateComponents

Overview

In Swift, this object bridges to DateComponents; use NSDateComponents when you need reference semantics or other Foundation-specific behavior.

NSDateComponents encapsulates the components of a date in an extendable, object-oriented manner. It’s used to specify a date by providing the temporal components that make up a date and time: hour, minutes, seconds, day, month, year, and so on. You can also use it to specify a duration of time, for example, 5 hours and 16 minutes. An NSDateComponents object is not required to define all the component fields. When a new instance of NSDateComponents is created, the date components are set to NSDateComponentUndefined.

An instance of NSDateComponents is not responsible for answering questions about a date beyond the information with which it was initialized. For example, if you initialize one with May 4, 2017, its weekday is NSDateComponentUndefined, not Thursday. To get the correct day of the week, you must create a suitable instance of NSCalendar, create an NSDate object using date(from:) and then use components(_:from:) to retrieve the weekday—as illustrated in the following example.

For more details, see Calendars, Date Components, and Calendar Units in Date and Time Programming Guide.

Topics

Setting a Calendar and Time Zone

Validating a Date

Accessing Years and Months

Accessing Weeks and Days

Accessing Hours and Seconds

Accessing Components as Calendrical Units

Initializers

Instance Properties