data formatting

36
7/18/2019 Data Formatting http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 1/36 Data Formatting Guide Data Management: Strings, Text, & Fonts 2011-03-08

Upload: sworna-vidhya-mahadevan

Post on 02-Mar-2016

30 views

Category:

Documents


0 download

DESCRIPTION

n

TRANSCRIPT

Page 1: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 1/36

Data Formatting GuideData Management: Strings, Text, & Fonts

2011-03-08

Page 2: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 2/36

Apple Inc.

© 2011 Apple Inc.

All rights reserved.

Nopart of this publicationmay be reproduced,

stored in a retrieval system, or transmitted, in

any form or by any means, mechanical,

electronic, photocopying, recording, or

otherwise, without prior written permission of 

Apple Inc., with the following exceptions: Any

person is hereby authorized to store

documentation on a single computer for

personal use only and to print copies of 

documentation for personal use provided that

the documentation containsApple’scopyright

notice.

The Apple logo is a trademark of Apple Inc.

No licenses, express or implied, are grantedwith respectto anyof thetechnology described

in this document. Apple retains all intellectual

property rights associated withthe technology

described in this document. This document is

intended to assist application developers to

develop applications only for Apple-labeled

computers.

Apple Inc.

1 Infinite Loop

Cupertino, CA 95014

408-996-1010

.Mac is a registered service mark of Apple Inc.

Apple,the Apple logo, Cocoa, iPhone, Mac,MacOS, Numbers, Objective-C, and Spaces are

trademarks of Apple Inc., registered in the

United States and other countries.

IOS is a trademark or registered trademark of 

Ciscoin the U.S. and other countriesand isused

under license.

Java is a registered trademarkof Oracleand/or

its affiliates.

Times is a registeredtrademark of Heidelberger

Druckmaschinen AG, available from Linotype

Library GmbH.

Even though Apple has reviewedthis document,APPLEMAKESNO WARRANTY OR REPRESENTATION,EITHER EXPRESS OR IMPLIED, WITH RESPECT TO

THIS DOCUMENT, ITS QUALITY, ACCURACY,MERCHANTABILITY, OR FITNESSFOR A PARTICULARPURPOSE. AS A RESULT, THIS DOCUMENT ISPROVIDED “AS IS,” ANDYOU, THEREADER, AREASSUMING THEENTIRE RISK AS TO ITSQUALITYAND ACCURACY.

IN NO EVENT WILL APPLE BE LIABLEFOR DIRECT,INDIRECT, SPECIAL, INCIDENTAL, ORCONSEQUENTIAL DAMAGESRESULTINGFROM ANYDEFECT OR INACCURACY IN THISDOCUMENT,evenif advised of the possibility of suchdamages.

THEWARRANTY ANDREMEDIES SETFORTH ABOVEAREEXCLUSIVEANDIN LIEU OFALL OTHERS, ORALOR WRITTEN, EXPRESS OR IMPLIED. No Appledealer, agent, or employee is authorized to makeanymodification, extension, or addition to this

warranty.Somestates do notallow theexclusion orlimitationof implied warranties or liability forincidental orconsequential damages, so the abovelimitation orexclusionmay not applyto you.This warrantygivesyouspecificlegal rights, and youmay alsohaveother rights which vary from state to state.

Page 3: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 3/36

Contents

Introduction to Data Formatting Programming Guide For Cocoa 7

Organization of This Document   7

Number Formatters 9

Use Formatter Styles to Present Numbers With the User’s Preferences   9

Use Format Strings to Specify Custom Formats   10

Percentages   10

Nomenclature   11

Date Formatters 13

Use Formatter Styles to Present Dates and Times With the User’s Preferences   13

Use Format Strings to Specify Custom Formats   14

Fixed Formats   14

Custom Formats for User-Visible Dates   15

Parsing Date Strings   16

Cache Formatters for Efficiency   17

Consider Unix Functions for Fixed-Format, Unlocalized Dates   19

Formatters and User Interface Elements 21

Associating a Formatter With a Cell   21Delegation Methods for Error Handling   22

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

Formatter Behavior Modes   23

Date Formatters   23

Number Formatters   24

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

Date Formatters   25

Number Formatters   25

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

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

Format String Syntax   29

Specifying Positive, Negative, and Zero Formats   30

NSDateFormatter Format String Syntax   31

32011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Page 4: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 4/36

Creating a Custom Formatter 33

Document Revision History 35

42011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Page 5: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 5/36

Page 6: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 6/36

62011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Page 7: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 7/36

You use formatters to interpret and create strings that represent other data types, and to validate the text

in text fields and other cells. Formatters are instances of subclasses of the abstract class, NSFormatter. The

Foundation framework provides two concrete subclasses of NSFormatter: NSNumberFormatter and

NSDateFormatter. (Core Foundation provides two equivalent opaque types: CFNumberFormatter and

CFDateFormatter. These are similar but are not toll-free bridged.) You can create a subclass of NSFormatter

for custom formatting.

In Cocoa, user interface cells that display text but have an arbitrary object as their content can use formatters

for both input and output. When a cell is displayed, the cell converts an arbitrary object to a textualrepresentation. How a cell displays theobject depends on whether or notthecell has an associated formatter.

If a cell has no formatter, the cell displays its content by using the localized representation of the object. If the cell has a formatter, the cell obtains a formatted string from the formatter. When the user enters text

into a cell, the cell converts the text to the underlying object using its formatter.

Organization of This Document

“Date Formatters” (page 13) describes how to use date formatters in Mac OS X v10.4 and later and iOS.

“Number Formatters” (page 9) describes how to use number formatters in Mac OS X v10.4 and later and

iOS.

“Formatters and User Interface Elements” (page 21) describes how to set a formatter for a user interfaceelement, and the interaction between an element and its formatter in Mac OS X.

“Date and Number Formatters on Mac OS X v10.0 to 10.3” (page 23) describes how to create and use date

and number formatters using Mac OS X versions 10.0 to 10.3.

“Creating a Custom Formatter” (page 33) outlines how to create custom formatter classes.

Organization of This Document 72011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Introduction to Data Formatting Programming

Guide For Cocoa

Page 8: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 8/36

8   Organization of This Document2011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Introduction to Data Formatting Programming Guide For Cocoa

Page 9: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 9/36

This article describes how you use number formatters using Mac OS X v10.4 and later and iOS. If you are

using Mac OS X v10.3 or earlier, you should read “Date and Number Formatters on Mac OS X v10.0 to10.3” (page 23).

NSNumberFormatter provides convenient two methods—stringFromNumber: and

numberFromString:—that you an useto create a stringrepresentationof a number andto create a number

object from a string respectively. To create a localized string representation of a number without creating a

formatter object, you can use the class method localizedStringFromNumber:numberStyle:.

If you have more sophisticated requirements when parsing a string, in addition to the methods inherited

from NSFormatter (such as getObjectValue:forString:errorDescription:), the

getObjectValue:forString:range:error: method allows you to specify a subrange of the string tobe parsed, and it returns the range of the string that was actually parsed. (In the case of failure, it indicateswhere the failure occurred.) It also returns an NSError object that can contain rich information about the

problem.

There are many attributes you can get and set on a number formatter. When you present information to the

user, you should typically simply use the NSNumberFormatter style constants to specify pre-defined sets

of attributes that determine how a formatted number is displayed. If you need to generate a representation

of a number in a precise format, however, you should use a format string.

Use Formatter Styles to Present Numbers With the User’s Preferences

NSNumberFormatter makes it easy for you to format different sorts of number using the settings a user

configured in the International preferences panel in System Preferences. The NSNumberFormatter style

constants—NSNumberFormatterDecimalStyle, NSNumberFormatterCurrencyStyle,

NSNumberFormatterPercentStyle, NSNumberFormatterScientificStyle, or

NSNumberFormatterSpellOutStyle (which generates a textual representation of a number)—specify

sets of attributes that determine how a number is displayed according to the user’s preferences.

You specify the style of a number formatter using setNumberStyle:. Listing 1 (page 9) illustrates how

you can format a date using formatter styles.

Listing 1   Formatting a number using a formatter style

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];

[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

NSString *formattedNumberString = [numberFormatter stringFromNumber:[NSNumber

numberWithFloat:122344.4563]];

NSLog(@"formattedNumberString: %@", formattedNumberString);

// Output for locale en_US: "formattedNumberString: formattedNumberString:

122,344.453"

Use Formatter Styles to Present Numbers With the User’s Preferences 92011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Number Formatters

Page 10: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 10/36

Use Format Strings to Specify Custom Formats

The format string uses the format patterns from the Unicode Technical Standard #35. The version of thestandard varies with release of the operating system:

 ●   Formatters in Mac OS X v10.6 use version tr35-10.

 ●   Formatters in Mac OS X v10.5 use version tr35-6.

 ●   Formatters in Mac OS X v10.4 use version tr35-4.

Note: Prior to Mac OS v10.6 and iOS v4.0, the implementation of getObjectValue:forString:errorDescription: would return YES and an object value even if onlypart of the string could be parsed. This is problematic because you cannot be sure what portion of the stringwas parsed. For applications linked on or after Mac OS v10.6 or iOS v4.0, this method instead returns an error

if part of the string cannot be parsed. You can use getObjectValue:forString:range:error: to get

the old behavior; it returns the range of the substring that was successfully parsed.

Mac OS X: Note that, since they work with general instances of NSFormatter, instances of NSCell onlyinvoke theNSFormattergetObjectValue:forString:errorDescription:method in Mac OS X v10.4.

For a v10.4-style number formatter, that method calls getObjectValue:forString:range:error:.

Note with the Unicode format string format, you should enclose literal text in the format string between

apostrophes ('').

You specifytheformatstringof a numberformatterusingsetPositiveFormat: andsetNegativeFormat:.

Listing 2 (page 10) illustrates how you can format a date using formatter styles.

Listing 2   Formatting a number using a format string

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];

[numberFormatter setPositiveFormat:@"###0.##"];

NSString *formattedNumberString = [numberFormatter stringFromNumber:[NSNumber

numberWithFloat:122344.4563]];

NSLog(@"formattedNumberString: %@", formattedNumberString);

// Output for locale en_US: "formattedNumberString: formattedNumberString:

122,344.45"

PercentagesIf you use a format string with a “%” character to format percentages, the results may be confusing. Considerthe following example:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];

[numberFormatter setPositiveFormat:@"0.00%;0.00%;-0.00%"];

NSNumber *four = [NSNumber numberWithFloat:4.0];

NSLog(@"%@", [numberFormatter stringFromNumber:four]);

// output: "400.00%"

10   Use Format Strings to Specify Custom Formats2011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Number Formatters

Page 11: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 11/36

Because the format string is specified to use percentages,NSNumberFormatter interprets the number four

as a fraction (where 1 is 100%) and renders it as such (4 = 4/1 = 400%).

If youwant to represent a numberas a percentage,youshould usetheNSNumberFormatterPercentStyle

style—this also ensures that percentages are formatted appropriately for the locale:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];[numberFormatter setNumberStyle:NSNumberFormatterPercentStyle];

NSNumber *four = [NSNumber numberWithFloat:4.0];

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

[numberFormatter setLocale:usLocale];

NSLog(@"en_US: %@", [numberFormatter stringFromNumber:four]);

// output: "en_US: 400%"

NSLocale *faLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"fa_IR"];

[numberFormatter setLocale:faLocale];

NSLog(@"fa_IR: %@", [numberFormatter stringFromNumber:four]);

// output: "fa_IR: "

Nomenclature

NSNumberFormatter provides several methods (such as setMaximumFractionDigits:) that allow you

to manage the number of fraction digits allowed as input by an instance. “Fraction digits” are the numbers

after the decimal separator (in English locales, the decimal separator is typically referred to as the “decimalpoint”).

Nomenclature 112011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Number Formatters

Page 12: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 12/36

12   Nomenclature2011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Number Formatters

Page 13: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 13/36

There are two basic methods you use to create a string representation of a date and to parse a string to get

a date object using a date formatter—dateFromString: and stringFromDate: respectively. You can

also usegetObjectValue:forString:range:error: if you need more control over the range of a string

you want to parse.

There are many attributes you can get and set on a date formatter. When you present information to theuser, you should typically simply use the NSDateFormatter style constants to specify pre-defined sets of 

attributes that determine how a formatted date is displayed. If you need to generate a representation of a

date in a precise format, however, you should use a format string.

If you need to parse a date string, the approach you take again depends on what you want to accomplish.

If you want to parse input from the user, you should typically use the style constants so as to match theirexpectations. If you want to parse dates you get from a database or a web service, for example, you shoulduse a format string.

In all cases, you should consider that formatters default to using the user’s locale (currentLocale)

superimposed with the user’s preference settings. If you want to use the user’s locale but without theirindividual settings, you can get the locale id from the current user locale (localeIdentifier) and make a

new "standard” locale with that, then set the standard locale as the formatter’s locale.

Use Formatter Styles to Present Dates and Times With the User’s

Preferences

NSDateFormatter makes it easy for you to format a date using the settings a user configured in the

International preferences panel in System Preferences. The NSDateFormatter style

constants—NSDateFormatterNoStyle,NSDateFormatterShortStyle,NSDateFormatterMediumStyle,

NSDateFormatterLongStyle,andNSDateFormatterFullStyle—specifysets of attributes that determine

how a date is displayed according to the user’s preferences.

You specify the style of the date and time components of a date formatter independently usingsetDateStyle: and setTimeStyle: respectively. Listing 1 (page 13) illustrates how you can format a

date using formatter styles. Notice the use of NSDateFormatterNoStyle to suppress the time component

and yield a string containing just the date.

Listing 1   Formatting a date using formatter styles

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateStyle:NSDateFormatterMediumStyle];

[dateFormatter setTimeStyle:NSDateFormatterNoStyle];

NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:162000];

NSString *formattedDateString = [dateFormatter stringFromDate:date];

Use Formatter Styles to Present Dates and Times With the User’s Preferences 132011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Date Formatters

Page 14: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 14/36

NSLog(@"formattedDateString: %@", formattedDateString);

// Output for locale en_US: "formattedDateString: Jan 2, 2001"

Use Format Strings to Specify Custom Formats

There are broadly speaking two situations in which you need to use custom formats:

1.   For fixed format strings, like Internet dates.

2.   For user-visible elements that don’t match any of the existing styles

Fixed Formats

To specify a custom fixed format for a date formatter, you use setDateFormat:. The format string uses the

format patterns from the Unicode Technical Standard #35. The version of the standard varies with release of the operating system:

 ●   Formatters in Mac OS X v10.6 use version tr35-10.

 ●   Formatters in Mac OS X v10.5 use version tr35-6.

 ●   Formatters in Mac OS X v10.4 use version tr35-4.

Although in principle a format string specifies a fixed format, by default NSDateFormater still takes the

user’s preferences (including the locale setting) into account. You must consider the following points whenusing format strings:

 ● NSDateFormatter treats the numbers in a string you parse as if they were in the user’s chosen calendar.

For example, if the user selects the Buddhist calendar, parsing the year 2010 yields an NSDate object

in 1467 in the Gregorian calendar. (For more about different calendrical systems and how to use them,

see Date and Time Programming Guide.)

 ●   In iOS, the user can override the default AM/PM versus 24-hour time setting. This may causeNSDateFormatter to rewrite the format string you set.

Note with the Unicode format string format, you should enclose literal text in the format string between

apostrophes ('').

The following example illustrates using a format string to generate a string:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm"];

NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:162000];

NSString *formattedDateString = [dateFormatter stringFromDate:date];

NSLog(@"formattedDateString: %@", formattedDateString);

// For US English, the output may be:

// formattedDateString: 2001-01-02 at 13:00

14   Use Format Strings to Specify Custom Formats2011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Date Formatters

Page 15: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 15/36

There are two things to note about this example:

1.   It uses yyyy to specify the year component. A common mistake is to use YYYY. yyyy specifies the

calendar year whereas YYYY specifies the year (of "Week of Year"), used in the ISO year-week calendar.

In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you

should use the calendar year.

2.   The representation of the time may be 13:00. In iOS, however, if the user has switched 24-Hour Time

to Off, the time may be 1:00 pm.

Custom Formats for User-Visible Dates

To display a date that contains a specific set of elements, you usedateFormatFromTemplate:options:locale:]. The method generates a format string with the date

components you want to use, but with the correct punctuation and order appropriate for the user (that is,customized for the user’s locale and preferences). You then use the format string to create a formatter.

For example, to create a formatter to display today’s day name, day, and month using the current locale, you

would write:

NSString *formatString = [NSDateFormatter dateFormatFromTemplate:@"EdMMM"

options:0

  locale:[NSLocale currentLocale]];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:formatString];

NSString *todayString = [dateFormatter stringFromDate:[NSDate date]];

NSLog(@"todayString: %@", todayString);

To understand the need for this, consider a situation where you want to display the day name, day, and

month. You cannot create this representation of a date using formatter styles (there is no style that omitsthe year). Neither, though, can you easily and consistently  create the representation correctly using formatstrings. Although at first glance it may seem straightforward, there’s a complication: a user from the United

States wouldtypically expect dates in theform, “Mon, Jan3”, whereasa user from Great Britain wouldtypicallyexpect dates in the form “Mon 31 Jan”.

The following example illustrates the point:

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

NSString *usFormatString = [NSDateFormatter dateFormatFromTemplate:@"EdMMM"

options:0 locale:usLocale];

NSLog(@"usFormatterString: %@", usFormatString);

// Output: usFormatterString: EEE, MMM d

NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];

NSString *gbFormatString = [NSDateFormatter dateFormatFromTemplate:@"EdMMM"

options:0 locale:gbLocale];

NSLog(@"gbFormatterString: %@", gbFormatString);

// Output: gbFormatterString: EEE d MMM

Use Format Strings to Specify Custom Formats 152011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Date Formatters

Page 16: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 16/36

Parsing Date Strings

In addition to the methods inherited from NSFormatter (such as

getObjectValue:forString:errorDescription:), NSDateFormatter adds dateFromString: and

getObjectValue:forString:range:error:. These methods make it easier for you to use anNSDateFormatter object directly in code, and make it easier to format dates into strings more complex

and more convenient ways than NSString formatting allows.

The getObjectValue:forString:range:error: method allows you to specify a subrange of the string

to be parsed, and it returns the range of the string that was actually parsed (in the case of failure, it indicateswhere the failure occurred). It also returns an NSError object that can contain richer information than the

failure stringreturned by thegetObjectValue:forString:errorDescription:method inheritedfrom

NSFormatter.

Note: Prior to Mac OS v10.6, the implementation of getObjectValue:forString:errorDescription:

would return YES and an object value even if only part of the string could be parsed. This is problematic

because you cannot be sure what portion of the string was parsed. For applications linked on or afterMac OS v10.6, this method instead returns an error if part of the string cannot be parsed. You can usegetObjectValue:forString:range:error: to get the old behavior; this method returns the range of 

the substring that was successfully parsed.

Mac OS X v10.4: Since they work with general instances of NSFormatter, instances of NSCell only invoke

the NSFormattergetObjectValue:forString:errorDescription: method in Mac OS X v10.4. For av10.4-style date formatter, that method calls getObjectValue:forString:range:error:.

The v10.4-style date formatter’s lenient parsing mode is not as forgiving as the “natural language” parsingof NSDateFormatter when the allowsNaturalLanguage option is enabled in the formatter. This has

advantages and disadvantages: users have to be more careful and perhaps thorough when typing in dates,but they are more likely to find that the value they were trying to input was correctly set to the value they

wanted rather than what the “natural language” parsing guessed they meant.

If you're working with fixed-format dates, you should first set the locale of the date formatter to somethingappropriate for your fixed format. In most cases the best locale to choose is en_US_POSIX, a locale that's

specifically designed to yield US Englishresults regardlessof bothuser andsystem preferences.en_US_POSIX

is also invariant in time (if the US, at some point in the future, changes the way it formats dates, en_US will

change to reflect the new behavior, but en_US_POSIX will not), and between platforms (en_US_POSIX

works the same on iPhone OS as it does on Mac OS X, and as it it does on other platforms).

Once you’ve set en_US_POSIX as the locale of the date formatter, you can then set the date format string

and the date formatter will behave consistently for all users.

Listing 2 (page 16) shows how to use NSDateFormatter for both of the roles described above. First it

creates a en_US_POSIXdate formatter to parse the incoming RFC3339 date string, using a fixed date format

string and UTC as the time zone. Next, it creates a standard date formatter to render the date as a string to

display to the user.

Listing 2   Parsing an RFC 3339 date-time

- (NSString *)userVisibleDateTimeStringForRFC3339DateTimeString:(NSString

*)rfc3339DateTimeString

16   Parsing Date Strings2011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Date Formatters

Page 17: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 17/36

  // Returns a user-visible date time string that corresponds to the

  // specified RFC 3339 date time string. Note that this does not handle

  // all possible RFC 3339 date time strings, just one of the most common

  // styles.

{

  NSString * userVisibleDateTimeString;

  NSDateFormatter * rfc3339DateFormatter;  NSLocale * enUSPOSIXLocale;

  NSDate * date;

  NSDateFormatter * userVisibleDateFormatter;

  userVisibleDateTimeString = nil;

  // Convert the RFC 3339 date time string to an NSDate.

  rfc3339DateFormatter = [[[NSDateFormatter alloc] init] autorelease];

  enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]

 autorelease];

  [rfc3339DateFormatter setLocale:enUSPOSIXLocale];  [rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];

  [rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

  date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];

  if (date != nil) {

  // Convert the NSDate to a user-visible date string.

  userVisibleDateFormatter = [[[NSDateFormatter alloc] init] autorelease];

  assert(userVisibleDateFormatter != nil);

  [userVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle];

  [userVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];

  userVisibleDateTimeString = [userVisibleDateFormatter

stringFromDate:date];

  }

  return userVisibleDateTimeString;

}

Cache Formatters for Efficiency

Creating a date formatter is not a cheap operation. If you are likely to use a formatter frequently, it is typically

more efficient to cache a single instance than to create and dispose of multiple instances. One approach isto use a static variable.

Listing 3 (page 17) re-implements the method shown in Listing 2 (page 16) to hold on to the date formattersfor subsequent reuse.

Listing 3   Parsing an RFC 3339 date-time using a cached formatter

static NSDateFormatter *sUserVisibleDateFormatter;

Cache Formatters for Efficiency 172011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Date Formatters

Page 18: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 18/36

- (NSString *)userVisibleDateTimeStringForRFC3339DateTimeString:(NSString

*)rfc3339DateTimeString

  // Returns a user-visible date time string that corresponds to the

  // specified RFC 3339 date time string. Note that this does not handle

  // all possible RFC 3339 date time strings, just one of the most common

  // styles.

{  static NSDateFormatter * sRFC3339DateFormatter;

  NSString * userVisibleDateTimeString;

  NSDate * date;

  // If the date formatters aren't already set up, do that now and cache them

  // for subsequence reuse.

  if (sRFC3339DateFormatter == nil) {

  NSLocale * enUSPOSIXLocale;

  sRFC3339DateFormatter = [[NSDateFormatter alloc] init];

  enUSPOSIXLocale = [[[NSLocale alloc]

initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];

  [sRFC3339DateFormatter setLocale:enUSPOSIXLocale];

  [sRFC3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];

  [sRFC3339DateFormatter setTimeZone:[NSTimeZone

timeZoneForSecondsFromGMT:0]];

  }

  if (sUserVisibleDateFormatter == nil) {

  sUserVisibleDateFormatter = [[NSDateFormatter alloc] init];

  [sUserVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle];

  [sUserVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];

  }

  // Convert the RFC 3339 date time string to an NSDate.

  // Then convert the NSDate to a user-visible date string.

  userVisibleDateTimeString = nil;

  date = [sRFC3339DateFormatter dateFromString:rfc3339DateTimeString];

  if (date != nil) {

  userVisibleDateTimeString = [sUserVisibleDateFormatter

stringFromDate:date];

  }

  return userVisibleDateTimeString;

}

If you cache date formatters (or any other objects that depend on the user’s current locale), you shouldsubscribe to theNSCurrentLocaleDidChangeNotificationnotification and update yourcached objects

when the current locale changes. The code in Listing 3 (page 17) defines sUserVisibleDateFormatter

outside of the method so that other code, not shown, can update it as necessary. In contrast,

sRFC3339DateFormatter is defined inside the method because, by design, it is not dependent on the

user’s locale settings.

18   Cache Formatters for Efficiency2011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Date Formatters

Page 19: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 19/36

Note: In theory you could use an auto-updating locale (autoupdatingCurrentLocale) to create a localethat automatically accounts for changes in the user’s locale settings. In practice this currently does not work 

with date formatters.

Consider Unix Functions for Fixed-Format, Unlocalized Dates

For date and times in a fixed, unlocalized format, that are always guaranteed to use the same calendar, it

may sometimes be easier and more efficient to use the standard C library functions strptime_l and

strftime_l.

Be aware that the C library also has the idea of a current locale. To guarantee a fixed date format, you shouldpass NULL as the loc parameter of these routines. This causes them to use the POSIX locale (also known as

the C locale), which is equivalent to Cocoa's en_US_POSIX locale, as illustrated in this example.

struct tm sometime;

const char *formatString = "%Y-%m-%d %H:%M:%S %z";(void) strptime_l("2005-07-01 12:00:00 -0700", formatString, &sometime, NULL);

NSLog(@"NSDate is %@", [NSDate dateWithTimeIntervalSince1970: mktime(&sometime)]);

// Output: NSDate is 2005-07-01 12:00:00 -0700

Consider Unix Functions for Fixed-Format, Unlocalized Dates 192011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Date Formatters

Page 20: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 20/36

20   Consider Unix Functions for Fixed-Format, Unlocalized Dates2011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Date Formatters

Page 21: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 21/36

This article describes how to associate a formatter with a cell in Cocoa. This article does not apply to iOS.

Associating a Formatter With a Cell

The easiest way to use a formatter is in Interface Builder to drag it from the palette onto a control such as atext field or a column in a table view. You can then configure the behavior you want using theinspector—typically you should use v10.4 behavior.

To create a formatterobjectprogrammatically andattach it to a cell, youallocate an instance of theformatterand set its format or style as you wish. You then use the NSCell setFormatter: method to associate the

formatter instance with a cell. The following code example creates and configures an instance of NSNumberFormatter, and applies it to the cell of an NSTextField object using the setFormatter:

method.

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];

[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

[[textField cell] setFormatter:numberFormatter];

Similarly, you can create and configure an instance of NSDateFormatter object programmatically. The

following example creates a date formatter then associates it with the cells of a form (contactsForm).

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateStyle:NSDateFormatterMediumStyle];

[dateFormatter setTimeStyle:NSDateFormatterNoStyle];

[[contactsForm cells] makeObjectsPerformSelector:@selector(setFormatter:)

  withObject:dateFormatter]

When a cell with a formatter object is copied, the new cell retains the formatter object rather than copyingit.

The type of object that you retrieve from a cell using the method objectValue depends upon the behavior

of the formatter:

 ●   For a number formatter, using Mac OS X version 10.0 behavior it would be a NSDecimalNumber object;

using 10.4 behavior it would be by default a NSNumber object.

 ●   For a date formatter, using Mac OS X version 10.0 behavior it would be a NSCalendarDateobject, using

v10.4 behavior it would be by default a NSDate object.

When the cell needs to display or edit itsvalue, it passes itsobject to the formatter which returns the formatted

string. When the user enters a string, or when a string is programmatically written in a cell (usingsetStringValue), the cell obtains the corresponding object from the formatter.

Associating a Formatter With a Cell 212011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Formatters and User Interface Elements

Page 22: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 22/36

Delegation Methods for Error Handling

NSControl has delegation methods for handling errors returned in implementations of NSFormatter’s

getObjectValue:forString:errorDescription:,

isPartialStringValid:proposedSelectedRange:originalString:originalSelectedRange:errorDescription: ,and isPartialStringValid:newEditingString:errorDescription: methods. These delegation

methods are, respectively, control:didFailToFormatString:errorDescription: and

control:didFailToValidatePartialString:errorDescription:.

22   Delegation Methods for Error Handling2011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Formatters and User Interface Elements

Page 23: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 23/36

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 usingv10.4 behavior.

Formatter Behavior Modes

On Mac OS X desktop version 10.4 and later, instances of an NSDateFormatter and NSNumberFormatter

can operate in two modes, 10.0 compatibility mode and 10.4 mode. The v10.4 behavior mode allows more

configurability and better localization; youshould useit forany new projects, andideally upgradeany existingcode that uses v10.0 behavior to use v10.4 behavior.

 ●   In the v10.0 compatibility mode, NSDateFormatter and NSNumberFormatter operate as they did in

Mac OS X from version 10.0 to 10.3, including the limitations and any outstanding bugs—see “Date andNumber Formatters on Mac OS X v10.0 to 10.3” (page 23).

 ●   On Mac OS X v10.4 and later, the behavior of the NSDateFormatter class is based on CFDateFormatter,

which is in turn based on the open-source ICU (International Components for Unicode) library.

(NSDateFormatter and CFDateFormatter, however, are not toll-free bridged.)

 ●   On Mac OS X v10.4 and later, the behavior of the NSNumberFormatter class is based on

CFNumberFormatter, which is in turn based on the open-source ICU (International Components for

Unicode) library. (NSNumberFormatter and CFNumberFormatter, however, are not toll-free bridged.)

For backwards binary compatibility, the default behavior in Mac OS X v10.4 is the v10.0 behavior. On Mac

OS X version 10.5 and later, however, the default is the v10.4 behavior.

The v10.4 methods do not do anything when invoked on a v10.0-style formatter, and return a generic returnvalue when required to return something. You should not invoke the v10.4methods on a v10.0-style formatter.On a v10.4-style formatter, the old methods map approximately to one or more new methods/attributes,

but the new methods should be used directly when possible.

iOS: The v10.0 compatibility mode is not available on iOS—only the 10.4 mode is available.

Date Formatters

You can set the default behavior of all instances of NSDateFormatter to the v10.4 behavior by invoking

theclassmethod,setDefaultFormatterBehavior:withtheargumentNSDateFormatterBehavior10_4.

You can also set the behavior for any instance individually by invoking setFormatterBehavior:.

Formatter Behavior Modes 232011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Date and Number Formatters on Mac OS X

v10.0 to 10.3

Page 24: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 24/36

You can set an application default (preference) to cause date formatters to be automatically converted to

the new style. Setthe NSMakeDateFormatters10_4 default to a BooleanYES/true value in the application’s

preferences. You must set the preference before any use is made of the NSDateFormatter class. Note that

the default has two effects:

1.   Date formatters you initialize with init adopt the v10.4 formatter behavior.

2.   Date formatters thatare unarchived fromeither non-keyed or keyed archivesare converted to v10.4-style

if the archived formatter has an un-customized format string at unarchive time.

The object type for date formatters that use the v10.0 behavior mode is NSCalendarDate, but for 10.4-style

formatters it is NSDate. If you want, you can configure a 10.4-style formatter to generate NSCalendarDate

objects using setGeneratesCalendarDates:. You are encouraged, however, to switch to using NSDate

for new style formatters.

Number Formatters

You can set the default behavior of all instances of NSNumberFormatter to the v10.4 behavior by invoking

the class method, setDefaultFormatterBehavior: with the argument

NSNumberFormatterBehavior10_4. You canalso setthebehavior forany instance individually by invoking

setFormatterBehavior:.

You can set an application default (preference) to cause number formatters to be automatically convertedto the new style. Set the NSMakeNumberFormatters10_4 default to a Boolean YES/true value in the

application’s preferences. You must set the preference before any use is made of the NSNumberFormatter

class. Note that the default has two effects:

1.   Number formatters you initialize with init adopt the v10.4 formatter behavior.

2.   Number formatters that are unarchived from either non-keyed or keyed archives are converted tov10.4-style if the archived formatter has an un-customized format string at unarchive time.

The object type for number formatters that use the v10.0 behavior mode is NSDecimalNumber, but for

10.4-style formatters it isNSNumber. If you want, you canconfigurea 10.4-style formatter to generate instances

of NSDecimalNumber using the method setGeneratesDecimalNumbers: (with the argument,YES). You

are encouraged, however, to use NSNumber for new style formatters.

Creating and Using Formatters Programmatically (Mac OS X 10.0 to10.3)

The easiest way to use a formatter is in Interface Builder to drag it from the palette onto a control such as atext 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 simplywant more fine-grained control over formatterobject (for example, to change thetext attributes of thevalues

displayed).

24   Creating and Using Formatters Programmatically (Mac OS X 10.0 to 10.3)2011-03-08 | © 2011 Apple Inc. All Rights Reserved.

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

Page 25: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 25/36

Date Formatters

Creating a Date Formatter

To create a date formatter programmatically, simply alloc and init it, following normal rules for memorymanagement.

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 StringSyntax(Mac OS X Versions10.0 to 10.3)” (page 27) fora 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 objectof the class NSGregorianDateFormatter; in Objective-C, it’s an objectof theclass 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. Forexample, a date format stringof "%b %d %Y"wouldyield 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 normalrules for memory management.

NSNumberFormatter *numberFormatter =  [[[NSNumberFormatter alloc] init] autorelease];

A common technique for assigning a format to an NSNumberFormatter object is to use the methodsetFormat,. 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.

Creating and Using Formatters Programmatically (Mac OS X 10.0 to 10.3) 252011-03-08 | © 2011 Apple Inc. All Rights Reserved.

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

Page 26: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 26/36

Page 27: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 27/36

// use setHasThousandSeparators:

[numberFormatter setHasThousandSeparators:YES];

// use setThousandSeparator:

[numberFormatter setThousandSeparator:@"_"];

If you use the methodsetHasThousandSeparatorswith an argument of noorfalse, it disables thousandseparators, 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 thecharacter the receiver uses to represent each separator. These methods don’t tell youwhether

separators are enabled. Even when separators are disabled, an NSNumberFormatter object still knows thecharacters it uses to represent separators.

Separators must be single characters. If you specify multiple characters in the arguments tosetThousandSeparator: 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 Gregoriandates), 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”. InCocoa, with natural-language processing for dates enabled, users can also express dates colloquially, suchas “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.

Date Format String Syntax (Mac OS X Versions 10.0 to 10.3) 272011-03-08 | © 2011 Apple Inc. All Rights Reserved.

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

Page 28: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 28/36

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 theformat string. The date conversionspecifiers in thetable belowcover a range of date conventions (differences

from the format used by strftime() are noted in parentheses):

DescriptionSpecifier

A '%' character%%

Abbreviated weekday name%a

Full weekday name%A

Abbreviated month name%b

Full month name%B

Shorthand for “%X %x", the locale format for date and time%c

Day of the month as a decimal number (01-31)%d

Same as %d but does not print the leading 0 for days 1 through 9 (unlike strftime(), does

not print a leading space)

%e

Milliseconds as a decimal number (000-999)%F

Hour based on a 24-hour clock as a decimal number (00-23)%H

Hour based on a 12-hour clock as a decimal number (01-12)%I

Day of the year as a decimal number (001-366)%j

Month as a decimal number (01-12)%m

Minute as a decimal number (00-59)%M

AM/PM designation for the locale%p

Second as a decimal number (00-59)%S

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

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

%x

Timeusing the timerepresentation for the locale (produces different results fromstrftime())%X

Year without century (00-99)%y

28   Date Format String Syntax (Mac OS X Versions 10.0 to 10.3)2011-03-08 | © 2011 Apple Inc. All Rights Reserved.

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

Page 29: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 29/36

DescriptionSpecifier

Year with century (such as 1990)%Y

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

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

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 andconvert 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. Numberformatters 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 tospecify both the input to and output from number formatter objects. The number formatter object in Cocoauses 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:

 ●   Numbers

Format strings can include numeric characters. Wherever you include a number in a format string, thenumber 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

numberformatter methods or functions. When youenable localizationfor a numberformatter, separatorsare 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. Forexample, 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 youput) 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

Number Format String Syntax (Mac OS X Versions 10.0 to 10.3) 292011-03-08 | © 2011 Apple Inc. All Rights Reserved.

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

Page 30: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 30/36

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, thedollar 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:

DisplayFormat String

1,019.55@"#,##0.00"

$1,019.55@"$#,##0.00"

1,019.55@"___,__0.00"

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:

 ● @"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—yournegative and positive formats should therefore both use the same approach.

30   Number Format String Syntax (Mac OS X Versions 10.0 to 10.3)2011-03-08 | © 2011 Apple Inc. All Rights Reserved.

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

Page 31: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 31/36

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 conversionspecifiers in thetable belowcover a range of date conventions (differences

from the format used by strftime() are noted in parentheses):

DescriptionSpecifier

A '%' character%%

Abbreviated weekday name%a

Full weekday name%A

Abbreviated month name%b

Full month name%B

Shorthand for “%X %x", the locale format for date and time%c

Day of the month as a decimal number (01-31)%d

Same as %d but does not print the leading 0 for days 1 through 9 (unlike strftime(), does

not print a leading space)

%e

Milliseconds as a decimal number (000-999)%F

Hour based on a 24-hour clock as a decimal number (00-23)%H

Hour based on a 12-hour clock as a decimal number (01-12)%I

Day of the year as a decimal number (001-366)%j

Month as a decimal number (01-12)%m

Minute as a decimal number (00-59)%M

AM/PM designation for the locale%p

Second as a decimal number (00-59)%S

NSDateFormatter Format String Syntax 312011-03-08 | © 2011 Apple Inc. All Rights Reserved.

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

Page 32: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 32/36

DescriptionSpecifier

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

Date using the date representation for the locale, including the time zone (produces different

results from strftime())

%x

Timeusing the timerepresentation for the locale (produces different results fromstrftime())%X

Year without century (00-99)%y

Year with century (such as 1990)%Y

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

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

32   NSDateFormatter Format String Syntax2011-03-08 | © 2011 Apple Inc. All Rights Reserved.

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

Page 33: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 33/36

Page 34: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 34/36

342011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Creating a Custom Formatter

Page 35: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 35/36

This table describes the changes to  Data Formatting Guide.

NotesDate

Significant update to the Date Formatting article.2011-03-08

Added links to Cocoa Core Competencies.2009-08-06

Corrected typographical errors.2009-05-25

Corrected typographical errors.2008-10-15

Updated links to Unicode format specifications.2007-03-20

Updated links to Unicode format definitions; added section on formattingPercentages to "NSNumberFormatter on Mac OS X 10.4".

2007-01-08

Added notes about the use of formatters with Interface Builder.2006-05-23

Moved discussion of string formatting and string format specifiers to String

Programming Guide.

Enhanced discussion of string formatting.2005-11-09

Changed thetitle from"Data Formatting."Updated to describe newfunctionalityin Mac OS X v10.4.2005-08-11

Added descriptions of NSString format specifiers %qx and %qX to Formatting

String Objects.

2004-08-31

Revised and updated content.2003-08-07

Clarified how cell contents are displayed when no formatter is set.2003-01-15

Revision history was added to existing document.2002-11-12

352011-03-08 | © 2011 Apple Inc. All Rights Reserved.

Document Revision History

Page 36: Data Formatting

7/18/2019 Data Formatting

http://slidepdf.com/reader/full/data-formatting-56d6840217b8b 36/36

Document Revision History