iOS Developer Library

Developer

Foundation Framework Reference NSDateComponents Class Reference

Options
Deployment Target:

On This Page
Language:

NSDateComponents

Inherits From


Conforms To


Import Statement


Swift

import Foundation

Objective-C

@import Foundation;

Availability


Available in iOS 2.0 and later

NSDateComponents encapsulates the components of a date in an extendable, object-oriented manner. It is 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. It can also be used 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 NSUndefinedDateComponent.

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 6, 2004, its weekday is NSUndefinedDateComponent, not Thursday. To get the correct day of the week, you must create a suitable instance of NSCalendar, create an NSDate object using dateFromComponents: and then use components:fromDate: to retrieve the weekday—as illustrated in the following example.

  • NSDateComponents *comps = [[NSDateComponents alloc] init];
  • [comps setDay:6];
  • [comps setMonth:5];
  • [comps setYear:2004];
  • NSCalendar *gregorian = [[NSCalendar alloc]
  • initWithCalendarIdentifier:NSGregorianCalendar];
  • NSDate *date = [gregorian dateFromComponents:comps];
  • [comps release];
  • NSDateComponents *weekdayComponents =
  • [gregorian components:NSWeekdayCalendarUnit fromDate:date];
  • int weekday = [weekdayComponents weekday];

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

  • This constant specifies that an NSDateComponents component is undefined.

    Declaration

    Swift

    var NSUndefinedDateComponent: Int { get }

    Objective-C

    enum { NSUndefinedDateComponent = 0x7fffffff };

    Constants

    • NSUndefinedDateComponent

      NSUndefinedDateComponent

      Specifies that the component is undefined.

      Available in iOS 2.0 and later

      Deprecated in iOS 8.0