< Previous PageNext Page > Hide TOC

Date and Number Formatters on Mac OS X v10.0 to 10.3

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.

Contents:

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


Creating and Using Formatters Programmatically (Mac OS X 10.0 to 10.3)

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).

Date Formatters

Creating a Date Formatter

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":

Number Formatters

Creating a Number Formatter

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.

Setting Text Attributes

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:

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];

Setting Separators

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 Format String Syntax (Mac OS X Versions 10.0 to 10.3)

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.”

Format String Syntax

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 '%' 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 (unlike strftime(), does not print a leading space)

%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-59)

%w

Weekday as a decimal number (0-6), where Sunday is 0

%x

Date using the date representation for the locale, including the time zone (produces different results from strftime())

%X

Time using the time representation for the locale (produces different results from strftime())

%y

Year without century (00-99)

%Y

Year with century (such as 1990)

%Z

Time zone name (such as Pacific Daylight Time; produces different results from strftime())

%z

Time zone offset in hours and minutes from GMT (HHMM)

Number Format String Syntax (Mac OS X Versions 10.0 to 10.3)

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.

Format String Syntax

Number format strings can include the following five types of character:

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

@"#,##0.00"

1,019.55

@"$#,##0.00"

$1,019.55

@"___,__0.00"

1,019.55

Specifying Positive, Negative, and Zero Formats

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:

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.

NSDateFormatter Format String Syntax

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 '%' 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 (unlike strftime(), does not print a leading space)

%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-59)

%w

Weekday as a decimal number (0-6), where Sunday is 0

%x

Date using the date representation for the locale, including the time zone (produces different results from strftime())

%X

Time using the time representation for the locale (produces different results from strftime())

%y

Year without century (00-99)

%Y

Year with century (such as 1990)

%Z

Time zone name (such as Pacific Daylight Time; produces different results from strftime())

%z

Time zone offset in hours and minutes from GMT (HHMM)



< Previous PageNext Page > Hide TOC


© 2008 Apple Inc. All Rights Reserved. (Last updated: 2008-10-15)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.