- Inherits from:
- NSObject
- Conforms to:
- NSCoding
- NSCopying
- NSObject (NSObject)
Declared in:
- Foundation/NSDate.h
- Foundation/NSCalendarDate.h
An NSDate object stores a date and time that can be compared to other dates and times.
- earlierDate: | Compares the receiver to the argument and returns the earlier of the two. |
- isEqualToDate: | Returns YES if the receiver and the argument are equal. |
- laterDate: | Compares the receiver to the argument and returns the later of the two. |
- timeIntervalSinceNow | Returns the number of seconds difference between the receiver and the current date and time. |
- timeIntervalSinceReferenceDate |
NSDate objects represent a single point in time. The NSDate cluster's single public superclass, NSDate, declares the programmatic interface for specific and relative time values.
The objects you create using NSDate are referred to as date objects. They are immutable objects. Because of the nature of class clusters, objects returned by the NSDate class are not instances of that abstract class but of one of its private subclasses. Although a date object's class is private, its interface is public, as declared by the abstract superclass, NSDate.
Generally, you instantiate a suitable date object by invoking one of the date... class methods.
The date classes adopt the NSCopying and NSCoding protocols.
NSDate is an abstract class that provides behavior for creating dates, comparing dates, representing dates, computing intervals, and similar functionality. It presents a programmatic interface through which suitable date objects are requested and returned. Date objects returned from NSDate are lightweight and immutable since they represent a invariant point in time. This class is designed to provide the foundation for arbitrary calendrical representations. Its subclass NSCalendarDate offers date objects that are suitable for representing dates according to western calendrical systems.
"Date" as used above implies clock time as well. The standard unit of time for date objects is a value typed as NSTimeInterval and expressed as seconds. The NSTimeInterval type makes possible a wide and fine-grained range of date and time values, giving accuracy within milliseconds for dates 10,000 years apart.
NSDate and its subclasses compute time as seconds relative to an absolute reference date. This reference date is the first instant of 1 January, 2001, Greenwich Mean Time (GMT). NSDate converts all date and time representations to and from NSTimeInterval values that are relative to this absolute reference date. A positive interval relative to a date represents a point in the future, a negative interval represents a time in the past.
Note: Cocoa implements time according to the Network Time Protocol (NTP) standard, which is based on Coordinated Universal Time. The current private implementations of NSDate follow the NTP standard. However, they do not account for leap seconds and therefore are not synchronized with International Atomic Time (the most accurate). |
Like various other Foundation classes, NSDate enables you to obtain operating-system functionality (dates and times) without depending on operating-system internals. It also provides a basis for the NSRunLoop and NSTimer classes, which use concrete date objects to implement local event loops and timers.
NSDate's sole primitive method, timeIntervalSinceReferenceDate, provides the basis for all the other methods in the NSDate interface. It returns a time value relative to an absolute reference date.
Use a date object to store a point in time. If you want to store the current time, use the date class method to create the date object. If you want to store some time other than the current time, use one of the dateWithTimeInterval... methods.
The dateWithTimeInterval... methods create date objects relative to a particular time, which the method name describes. You specify (in seconds) how much more recent or how much more in the past you want your date object to be. To specify a date that occurs earlier than the method's reference date, use a negative number of seconds. The code fragment below defines two date objects. tomorrow is exactly 24 hours from the current date and time, and yesterday is exactly 24 hours earlier than the current date and time.
NSTimeInterval secondsPerDay = 24 * 60 * 60; NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay]; NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:-secondsPerDay];
To get new date objects with date-and-time values adjusted from existing date objects, use addTimeInterval:.
NSTimeInterval secondsPerDay = 24 * 60 * 60; NSDate *today = [NSDate date]; NSDate *tomorrow, yesterday; tomorrow = [today addTimeInterval:secondsPerDay]; yesterday = [today addTimeInterval:-secondsPerDay];
The NSDate class cluster provides, for your convenience, a public concrete subclass of NSDate that satisfies many requirements for dates and times. This subclass, NSCalendarDate, enables you to represent dates as arbitrary strings, to create new date objects from string representations, to extract date and time elements from date objects, and to do other calendar-related functions.
To obtain the difference between a date object and another point in time, send a timeInterval... message to the date object. For instance, timeIntervalSinceNow gives you the time, in seconds, between the current time and the receiving date object.
To compare dates, use the isEqualToDate:, compare:, laterDate:, and earlierDate: methods. These methods perform exact comparisons, which means they will detect subsecond differences between dates. You might want to compare dates with a less fine granularity. For example, you might want to consider two dates equal if they are within a minute of each other. If this is the case, use timeIntervalSinceDate: to compare the two dates or use NSCalendarDate objects instead. The following code shows how to use timeIntervalSinceDate: to see if two dates are within one minute (60 seconds) of each other.
if (fabs([date2 timeIntervalSinceDate:date1]) < 60) ...
To represent your date object as an NSString, use description description, prints out the date in the format YYYY-MM-DD HH:MM:SS ±HHMM, where ±HHMM represents the time zone offset in hours and minutes from GMT. (Adding the offset to the specific time yields the equivalent GMT.) The following keys in the locale dictionary affect NSDates:
Key | Description |
NSTimeDateFormatString |
Specifies how dates with times are printed. The default is to use abbreviated months and days with a 24 hour clock, as in "Sun Jan 01 23:00:00 +6 2001." |
NSAMPMDesignation |
Specifies how the morning and afternoon designations are printed. The default is AM and PM. |
NSMonthNameArray |
Specifies the names for the months. |
NSShortMonthNameArray |
Specifies the abbreviations for the months. |
NSWeekDayNameArray |
Specifies the names for the days of the week. |
NSShortWeekDayNameArray |
Specifies the abbreviations for the days of the week. |
If you want to subclass NSDate to obtain behavior different than that provided by the private subclasses, you must do these things:
Your subclass may use a different reference date than the absolute reference date used by NSDate (the first instance of 1 January 2001, GMT). If it does, it must still use the absolute reference date in its implementations of the methods timeIntervalSinceReferenceDate and initWithTimeIntervalSinceReferenceDate:. 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.
NSDate provides the following constant as a convenience:
Constant | Type | Description |
NSTimeIntervalSince1970 |
NSTimeInterval | 978307200 |
NSCopying
- - copyWithZone:
NSCoding
- - encodeWithCoder:
- - initWithCoder:
- Creating an NSDate instance
- + date
- + dateWithNaturalLanguageString:
- + dateWithNaturalLanguageString:locale:
- + dateWithString:
- + dateWithTimeIntervalSinceNow:
- + dateWithTimeIntervalSinceReferenceDate:
- + dateWithTimeIntervalSince1970:
- + distantFuture
- + distantPast
- - init
- - initWithString:
- - initWithTimeIntervalSinceNow:
- - initWithTimeInterval:sinceDate:
- - initWithTimeIntervalSinceReferenceDate:
- - addTimeInterval:
- Comparing dates
- - isEqualToDate:
- - earlierDate:
- - laterDate:
- - compare:
- Getting time intervals
- - timeIntervalSinceDate:
- - timeIntervalSinceNow
- + timeIntervalSinceReferenceDate
- - timeIntervalSinceReferenceDate
- - timeIntervalSince1970
- Representing dates as NSStrings
- - description
- - descriptionWithCalendarFormat:timeZone:locale:
- - descriptionWithLocale:
- Converting to an NSCalendarDate object
- - dateWithCalendarFormat:timeZone:
+ (NSTimeInterval)timeIntervalSinceReferenceDate
See Also: - timeIntervalSinceReferenceDate, - timeIntervalSinceDate:, - timeIntervalSince1970, - timeIntervalSinceNow
+ (id)date
A typical example of using date to get the current date is:
NSDate *today = [NSDate date];
+ dateWithNaturalLanguageString:(NSString
*)string
+ dateWithNaturalLanguageString:(NSString
*)string locale:(NSDictionary
*)localeDictionary
Key | Description |
NSDateTimeOrdering |
Determines how to use ambiguous numbers. Specify this value as a permutation of the letters M (month), D (day), Y (year), and H (hour). For example, MDYH treats "2/3/95 10" as the 3rd day of February 1995 at 10:00am, whereas DMYH treats the same value as the 2nd day of March 1995 at 10:00am. If fewer numbers are specified than are needed, the numbers are prioritized to satisfy day first, then the month, and then the year. For example, if you supply only the value 12, it means the 12th day of this month in this year because the day must be specified. If you supply "2 12" it means either February 12 or December 2, depending on if the ordering is "MDYH" or "DMYH." |
NSEarlierTimeDesignations |
An array of strings that denote a time in the past. These are adjectives that modify values from NSYearMonthWeekDesignations. The defaults are "prior," "last," "past," and "ago." |
NSHourNameDesignations |
Strings that identify the time of day. These strings should be bound to an hour. The default is this array of arrays: (0, midnight), (12, noon, lunch), (10, morning), (14, afternoon), (19, dinner). |
NSLaterTimeDesignations |
An array of strings that denote a time in the future. This is an adjective that modifies a value from NSYearMonthWeekDesignations. The default is "next." |
NSNextDayDesignations |
A string that identifies the day after today. The default is "tomorrow." |
NSNextNextDayDesignations |
A string that identifies the day after tomorrow. The default is "nextday." |
NSPriorDayDesignations |
A string that identifies the day before today. The default is "yesterday." |
NSThisDayDesignations |
A string that identifies what this day is called. The default is "today." |
NSYearMonthWeekDesignations |
An array of strings that specify the word for year, month, and week in the current locale. The defaults are "year," "month," and "week." |
See Also: + dateWithNaturalLanguageString:
+ (id)dateWithString:(NSString
*)aString
See Also: - initWithString:
+ (id)dateWithTimeIntervalSince1970:(NSTimeInterval)seconds
This method is useful for creating NSDate objects from time_t values returned by BSD system functions.
See Also: - timeIntervalSince1970
+ (id)dateWithTimeIntervalSinceNow:(NSTimeInterval)seconds
See Also: - initWithTimeIntervalSinceNow:
+ (id)dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)seconds
See Also: - initWithTimeIntervalSinceReferenceDate:
+ (id)distantFuture
You
can pass this value where an NSDate is required to have the date
argument essentially ignored. For example, the NSWindow method nextEventMatchingMask:untilDate:inMode:dequeue: returns nil
if
an event specified in the event mask does not happen before the
specified date. You can use the object returned by distantFuture as
the date argument to wait indefinitely for the event to occur.
myEvent = [myWindow nextEventMatchingMask:myEventMask untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES];
See Also: + distantPast
+ (id)distantPast
See Also: + distantFuture
- (id)addTimeInterval:(NSTimeInterval)seconds
See Also: - initWithTimeInterval:sinceDate:, - timeIntervalSinceDate:
- (NSComparisonResult)compare:(NSDate
*)anotherDate
NSOrderedSame
.
If the receiving object in the comparison is more recent than anotherDate,
the method returns NSOrderedDescending
.
If it is older, it returns NSOrderedAscending
. This method detects subsecond differences between dates. If you want to compare dates with a less fine granularity, use timeIntervalSinceDate: to compare the two dates or use NSCalendarDate objects instead.
See Also: - earlierDate:, - isEqual: (NSObject protocol), - laterDate:
- (NSCalendarDate *)dateWithCalendarFormat:(NSString
*)formatString
timeZone:(NSTimeZone *)timeZone
nil
for either or both
of these arguments, the default format string and time zone are
assumed. (The default time zone is the one specific to the current
locale; the default format string, which is "%Y-%m-%d %H:%M:%S
%z", conforms to the international format YYYY-MM-DD HH:MM:SS
±HHMM.) The conversion specifiers for formatString cover a range of date conventions:
Specifier | Description |
%% | a '%' character |
%a | abbreviated weekday name |
%A | full weekday name |
%b | abbreviated month name |
%B | full month name |
%c | shorthand for %X %x, the locale format for date and time |
%d | day of the month as a decimal number (01-31) |
%e | same as %d but does not print the leading 0 for days 1 through 9 |
%F | milliseconds as a decimal number (000 - 999) |
%H | hour based on a 24-hour clock as a decimal number (00-23) |
%I | hour based on a 12-hour clock as a decimal number (01-12) |
%j | day of the year as a decimal number (001-366) |
%m | month as a decimal number (01-12) |
%M | minute as a decimal number (00-59) |
%p | AM/PM designation for the locale |
%S | second as a decimal number (00-61) |
%w | weekday as a decimal number (0-6), where Sunday is 0 |
%x | date using the date representation for the locale |
%X | time using the time representation for the locale |
%y | year without century (00-99) |
%Y | year with century (such as 1990) |
%Z | time zone name (such as Pacific Daylight Time) |
%z | time zone offset in hours and minutes from GMT (HHMM) |
See Also: - description, - descriptionWithCalendarFormat:timeZone:locale:, - descriptionWithLocale:, + dateWithString:calendarFormat: (NSCalendarDate)
- (NSString *)description
See Also: - description (NSCalendarDate)
- (NSString *)descriptionWithCalendarFormat:(NSString
*)formatString
timeZone:(NSTimeZone *)aTimeZone
locale:(NSDictionary *)localeDictionary
nil
for
one of these arguments, its default value is assumed. (The default
time zone is the one specific to the current locale; the default
format string, which is "%Y-%m-%d %H:%M:%S %z", conforms to
the international format YYYY-MM-DD HH:MM:SS ±HHMM.) You could use this method to print the current time as follows:
sprintf(aString, "The current time is %s\n", [[[NSDate date] descriptionWithCalendarFormat:@"%H:%M:%S %Z" timeZone:nil locale:nil] cString]);
See Also: - description, - descriptionWithCalendarFormat:locale: (NSCalendarDate), - descriptionWithLocale:
- (NSString *)descriptionWithLocale:(NSDictionary
*)localeDictionary
See Also: - description, - descriptionWithCalendarFormat:timeZone:locale:, - descriptionWithLocale: (NSCalendarDate)
- (NSDate *)earlierDate:(NSDate
*)anotherDate
See Also: - compare:, - isEqual: (NSObject protocol), - laterDate:
- (id)init
See Also: + date, - initWithTimeIntervalSinceReferenceDate:
- (id)initWithString:(NSString
*)description
See Also: + dateWithString:, - description
- (id)initWithTimeInterval:(NSTimeInterval)seconds
sinceDate:(NSDate *)anotherDate
- (id)initWithTimeIntervalSinceNow:(NSTimeInterval)seconds
See Also: + dateWithTimeIntervalSinceNow:
- (id)initWithTimeIntervalSinceReferenceDate:(NSTimeInterval)seconds
This method is the designated initializer for the NSDate class and is declared primarily for the use of subclasses of NSDate. When you subclass NSDate to create a concrete date class, you must override this method.
See Also: + dateWithTimeIntervalSinceReferenceDate:
- (BOOL)isEqualToDate:(NSDate
*)anotherDate
See Also: - compare:, - earlierDate:, - isEqual: (NSObject protocol), - laterDate:
- (NSDate *)laterDate:(NSDate
*)anotherDate
See Also: - compare:, - earlierDate:, - isEqual: (NSObject protocol)
- (NSTimeInterval)timeIntervalSince1970
See Also: - timeIntervalSinceDate:, - timeIntervalSinceNow, - timeIntervalSinceReferenceDate
- (NSTimeInterval)timeIntervalSinceDate:(NSDate
*)anotherDate
See Also: - timeIntervalSince1970, - timeIntervalSinceNow, - timeIntervalSinceReferenceDate
- (NSTimeInterval)timeIntervalSinceNow
See Also: - timeIntervalSinceDate:, - timeIntervalSince1970, - timeIntervalSinceReferenceDate
- (NSTimeInterval)timeIntervalSinceReferenceDate
This is the primitive method for NSDate. If you subclass NSDate, you must override this method with your own implementation for it.
See Also: - timeIntervalSinceDate:, - timeIntervalSince1970, - timeIntervalSinceNow, + timeIntervalSinceReferenceDate