This article describes how to create and use formatters on Mac OS X 10.0 to 10.3, and the format string patterns available when you use a formatter in v10.0 mode. You are strongly encouraged to migrate to using v10.4 behavior.
Creating and Using Formatters Programmatically (Mac OS X 10.0 to 10.3)
Date Format String Syntax (Mac OS X Versions 10.0 to 10.3)
Number Format String Syntax (Mac OS X Versions 10.0 to 10.3)
NSDateFormatter Format String Syntax
The easiest way to use a formatter is in Interface Builder to drag it from the palette onto a control such as a text field or a column in a table view. You can also create and manipulate instances of the formatter programmatically. Do this if you’re not using Interface Builder to create your user interface or if you simply want more fine-grained control over formatter object (for example, to change the text attributes of the values displayed).
To create a date formatter programmatically, simply alloc and init it, following normal rules for memory management.
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] |
initWithDateFormat:@"%b %1d %Y" allowNaturalLanguage:NO]; |
Note the use of 1
in the date field to specify a width of 1—this ensures that single digit dates are output without a leading 0
. See “Date Format String Syntax (Mac OS X Versions 10.0 to 10.3)” for a complete description of the syntax of the corresponding date format strings.
You must specify a format string whenever you create a date formatter (In Java, a Gregorian date formatter is an object of the class NSGregorianDateFormatter; in Objective-C, it’s an object of the class NSDateFormatter.) This format is a string that contains specifiers that are very similar to those used in the standard C library function strftime()
. When a date formatter converts a date to a string, it uses this same format string. For example, a date format string of "%b %d %Y"
would yield strings such as "Mar 15 1994"
. This code example creates a date formatter object that yields date strings such as "7/21/2003"
:
To create an NSNumberFormatter object programmatically, simply use alloc and init, and follow the normal rules for memory management.
NSNumberFormatter *numberFormatter = |
[[[NSNumberFormatter alloc] init] autorelease]; |
A common technique for assigning a format to an NSNumberFormatter object is to use the method setFormat
,. You can also specify the format of positive, zero, and negative values in one format string as follows:
// specify just positive format |
[numberFormatter setFormat:@"$#,##0.00"]; |
// specify positive and negative formats |
[numberFormatter setFormat:@"$#,##0.00;($#,##0.00)"]; |
// specify positive, zero, and negative formats |
[numberFormatter setFormat:@"$#,###.00;0.00;($#,##0.00)"]; |
As an alternative to using the setFormat:
method, you can use the setPositiveFormat:
and setNegativeFormat:
methods.
In NSNumberFormatter, positive, negative, zero, nil, and “not a number” values are represented as attributed strings (NSAttributedString objects). With attributed strings, you can apply attributes such as color or font to a range of characters in a string. (For more information on NSAttributedString, see Attributed Strings Programming Guide.)
Because the values displayed by NSNumberFormatter are attributed strings, you can customize aspects of their appearance, such as their color and font. The NSNumberFormatter methods you use to do this are as follows:
textAttributesForPositiveValues
setTextAttributesForPositiveValues:
textAttributesForNegativeValues
setTextAttributesForNegativeValues:
attributedStringForZero
setAttributedStringForZero:
attributedStringForNil
setAttributedStringForNil:
attributedStringForNotANumber
setAttributedStringForNotANumber:
For example, in the output of this code example, negative values are displayed in red:
NSNumberFormatter *numberFormatter = |
[[[NSNumberFormatter alloc] init] autorelease]; |
NSMutableDictionary *newAttrs = [NSMutableDictionary dictionary]; |
[numberFormatter setFormat:@"$#,##0.00;($#,##0.00)"]; |
[newAttrs setObject:[NSColor redColor] forKey:@"NSColor"]; |
[numberFormatter setTextAttributesForNegativeValues:newAttrs]; |
[[textField cell] setFormatter:numberFormatter]; |
NSNumberFormatter supports two kinds of separators: thousand and decimal. By default these separators are represented by, respectively, the comma (,
) and period (.
) characters. By default, they’re disabled.
All of the following Java statements have the effect of enabling thousand separators:
// use setFormat: |
numberFormatter.setFormat("#,###"); |
// use setHasThousandSeparators: |
numberFormatter.setHasThousandSeparators(true); |
// use setThousandSeparator: |
numberFormatter.setThousandSeparator("_"); |
And all of the following Objective-C statements also have the effect of enabling thousand separators:
// use setFormat: |
[numberFormatter setFormat:@"#,###"]; |
// use setHasThousandSeparators: |
[numberFormatter setHasThousandSeparators:YES]; |
// use setThousandSeparator: |
[numberFormatter setThousandSeparator:@"_"]; |
If you use the method setHasThousandSeparators
with an argument of no
or false
, it disables thousand separators, even if you’ve set them through another means.
Both of the following Java statements have the effect of enabling decimal separators:
// use setFormat: |
numberFormatter.setFormat("0.00"); |
// use setDecimalSeparator: |
numberFormatter.setDecimalSeparator("-"); |
And both of the following Objective-C statements also have the effect of enabling decimal separators:
// use setFormat: |
[numberFormatter setFormat:@"0.00"]; |
// use setDecimalSeparator: |
[numberFormatter setDecimalSeparator:@"-"]; |
When you enable or disable separators, it affects positive and negative formats. Consequently, both formats must use the same separator scheme.
Even though, you can use the thousandSeparator
and decimalSeparator
methods to return a string containing the character the receiver uses to represent each separator. These methods don’t tell you whether separators are enabled. Even when separators are disabled, an NSNumberFormatter object still knows the characters it uses to represent separators.
Separators must be single characters. If you specify multiple characters in the arguments to setThousandSeparator:
and setDecimalSeparator:
, only the first character is used.
You can’t use the same character to represent thousand and decimal separators.
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) |
Number formatters format the textual representation of user interface cells that contain number objects and convert textual representations of numeric values into number objects. The representation encompasses integers, floats, and doubles. Floats and doubles can be formatted to a specified decimal position. Number formatters can also impose ranges on the numeric values cells can accept.
You create number formatter objects by specifying a number format string. This format string is used to specify both the input to and output from number formatter objects. The number formatter object in Cocoa uses this syntax when specifying the format string as described below. Note that you can specify different formats for positive, negative, and zero number values.
Number format strings can include the following five types of character:
Numbers
Format strings can include numeric characters. Wherever you include a number in a format string, the number is displayed unless an input character in the same relative position overwrites it. For example, if you have the positive format string @"9,990.00"
and the value 53.88
is entered into a cell to which the format has been applied, the cell displays the value as 9,953.88
.
Separators
Format strings can include the period character (.
) as a decimal separator, and comma character (,
) as a thousand separator. If you want to use other characters as separators, you can change them using the number formatter methods or functions. When you enable localization for a number formatter, separators are converted to characters appropriate to the environment in which the application is running.
Placeholders
You use the pound sign character (#
) to represent numeric characters that will be input by the user. For example, suppose you have the positive format @"$#,##0.00"
. If the characters 76329
are entered into a cell to which the format has been applied, they are displayed as $76,329.00
. Strictly speaking, however, you don’t need to use placeholders. The format strings @",0.00"
, @"#,#0.00"
, and @"#,##0.00"
are functionally equivalent. In other words, including separator characters in a format string signals a number formatter to use the separators, regardless of whether you use (or where you put) placeholders. The placeholder character’s chief virtue lies in its ability to make format strings more human readable, which is especially useful if you’re displaying formats in the user interface.
Spaces
To include a space in a format string, use the underscore character (_
). This character inserts a space if no numeric character has been input to occupy that position.
Currency
The dollar sign character ($
) is normally treated just like any other character that doesn’t play a special role in a number formatter. However, when you enable localization for a number formatter object, the dollar sign character is converted to the currency symbol appropriate for the environment in which the application is running.
All other characters specified in a number format string are displayed as typed. The following table shows examples of the how the value 1019.55
is displayed for different positive formats:
Format String | Display |
---|---|
| 1,019.55 |
| $1,019.55 |
| 1,019.55 |
When creating a number formatter object, you can also specify a different format for positive, negative, and zero values, all using one format string. The format string can be one of the following:
@"
positiveFormat"
For example, @"$###,##0.00"
(a single number format string as described above).
@"
positiveFormat;
negativeFormat"
For example, @"###,##0.00;(###,##0.00)"
.
@"
positiveFormat;
zeroFormat;
negativeFormat"
For example, @"$###,###.00;0.00;($###,##0.00)"
. Note that zero formats are treated as string constants.
No matter which option you choose, you’re required to specify a format for positive values only. If you don’t specify a format for negative and zero values, a default format based on the positive value format is used. For example, if your positive value format is "#,##0.00"
, an input value of "0"
is displayed as "0.00"
.
If you don’t specify a format for negative values, the format specified for positive values is used, preceded by a minus sign (-
).
If you specify a separate format for negative values, its separators should be parallel to those specified in the positive format string. In number formatters, separators are either enabled or disabled for all formats—your negative and positive formats should therefore both use the same approach.
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) |
© 2008 Apple Inc. All Rights Reserved. (Last updated: 2008-10-15)