Date formatters format the textual representation of cells that contain date objects (including Gregorian dates), and convert textual representations of dates and times into date objects. You can express the representation of dates and times very flexibly: “Thu 22 Dec 1994” is just as acceptable as “12/22/94”. In Cocoa, with natural-language processing for dates enabled, users can also express dates colloquially, such as “today,” “day after tomorrow,” and “a month from today.”
You create date formatter objects by specifying a format string using strftime-style conversion specifiers. For example, the format string "%m/%d/%y" yields strings such as "01/02/01", and "%1m/%1d/%Y" yields strings such as "1/2/2001", as illustrated in the following example.
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] |
initWithDateFormat:@"%1m/%1d/%Y" allowNaturalLanguage:NO] autorelease]; |
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:118800]; |
NSString *formattedDateString = [dateFormatter stringFromDate:date]; |
NSLog(@"formattedDateString: %@", formattedDateString); |
// Output: formattedDateString: 1/2/2001 |
You use the format string is used to specify both the input to and the output from date formatter objects. All the date formatter objects in both Foundation and Core Foundation use this syntax when specifying the format string. The date conversion specifiers in the table below cover a range of date conventions (differences from the format used by strftime() are noted in parentheses):
Specifier | Description |
|---|---|
| A |
| Abbreviated weekday name |
| Full weekday name |
| Abbreviated month name |
| Full month name |
| Shorthand for “ |
| Day of the month as a decimal number (01-31) |
| Same as |
| Milliseconds as a decimal number (000-999) |
| Hour based on a 24-hour clock as a decimal number (00-23) |
| Hour based on a 12-hour clock as a decimal number (01-12) |
| Day of the year as a decimal number (001-366) |
| Month as a decimal number (01-12) |
| Minute as a decimal number (00-59) |
| AM/PM designation for the locale |
| Second as a decimal number (00-59) |
| Weekday as a decimal number (0-6), where Sunday is 0 |
| Date using the date representation for the locale, including the time zone (produces different results from |
| Time using the time representation for the locale (produces different results from |
| Year without century (00-99) |
| Year with century (such as 1990) |
| Time zone name (such as Pacific Daylight Time; produces different results from |
| Time zone offset in hours and minutes from GMT (HHMM) |
Last updated: 2007-03-20