NSDate objects encapsulate a single point in time, independent of any particular calendrical system or time zone. Date objects are immutable, representing an invariant time interval relative to an absolute reference date (00:00:00 UTC on 1 January 2001).
- iOS 2.0+
- macOS 10.0+
- tvOS 9.0+
- watchOS 2.0+
NSDate class provides methods for comparing dates, calculating the time interval between two dates, and creating a new date from a time interval relative to another date.
NSDate objects can be used in conjunction with
DateFormatter objects to create localized representations of dates and times, as well as with
NSCalendar objects to perform calendar arithmetic.
The major reason for subclassing
NSDate is to create a class with convenience methods for working with a particular calendrical system. But you could also require a custom
NSDate class for other reasons, such as to get a date and time value that provides a finer temporal granularity.
Methods to Override
If you want to subclass
NSDate to obtain behavior different than that provided by the private or public subclasses, you must do these things:
Declare a suitable instance variable to hold the date and time value (relative to an absolute reference date).
timeIntervalSinceReferenceDateinstance method to provide the correct date and time value based on your instance variable.
init(timeIntervalSinceReferenceDate:), one of the designated initializer methods.
If you are creating a subclass that represents a calendrical system, you must also define methods that partition past and future periods into the units of this calendar.
NSDate class adopts the
NSCoding protocols, your subclass must also implement all of the methods in these protocols.
Your subclass may use a different reference date than the absolute reference date used by
NSDate (00:00:00 UTC on 1 January 2001). If it does, it must still use the absolute reference date in its implementations of the methods
init(timeIntervalSinceReferenceDate:). That is, the reference date referred to in the titles of these methods is the absolute reference date. If you do not use the absolute reference date in these methods, comparisons between
NSDate objects of your subclass and
NSDate objects of a private subclass will not work.