Mac Developer Library

Developer

Foundation Framework Reference NSDateFormatter Class Reference

Options
Deployment Target:

On This Page
Language:

NSDateFormatter

Instances of NSDateFormatter create string representations of NSDate objects, and convert textual representations of dates and times into NSDate objects. You can express the representation of dates and times flexibly using pre-set format styles or custom format strings.

Date formats for user-visible strings should be configured using the styles configured by the user—use dateStyle, timeStyle, and appropriate style constants (defined in NSDateFormatterStyle) to choose between them.

  1. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  2. dateFormatter.timeStyle = NSDateFormatterNoStyle;
  3. dateFormatter.dateStyle = NSDateFormatterMediumStyle;
  4. NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:118800];
  5. NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
  6. [dateFormatter setLocale:usLocale];
  7. NSLog(@"Date for locale %@: %@",
  8. [[dateFormatter locale] localeIdentifier], [dateFormatter stringFromDate:date]);
  9. // Output:
  10. // Date for locale en_US: Jan 2, 2001
  11. NSLocale *frLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"];
  12. [dateFormatter setLocale:frLocale];
  13. NSLog(@"Date for locale %@: %@",
  14. [[dateFormatter locale] localeIdentifier], [dateFormatter stringFromDate:date]);
  15. // Output:
  16. // Date for locale fr_FR: 2 janv. 2001

If for some reason you need to define a format that was not specified by the user at the system level, you can set individual attributes such as the locale, time zone, calendar, format string, and various textual strings like the month names.

Note that although setting a format string (dateFormat) in principle specifies an exact format, in practice it may nevertheless also be overridden by a user’s preferences—see Data Formatting Guide for more details.

Formatter Behaviors and OS Versions

OS X v10.4 introduced the modern behavior for NSDateFormatter. See Data Formatting Guide for a full description of the old and new behaviors.

In OS X v10.5 and later, NSDateFormatter defaults to the modern behavior. If necessary, you can set the default class behavior using setDefaultFormatterBehavior:, or you can set the behavior for an instance using formatterBehavior.

  • Initializes and returns an NSDateFormatter instance that uses the OS X v10.0 formatting behavior and the given date format string in its conversions.

    Declaration

    Objective-C

    - (id)initWithDateFormat:(NSString *)format allowNaturalLanguage:(BOOL)flag

    Parameters

    format

    The format for the receiver. See Data Formatting Guide for a list of conversion specifiers permitted in date format strings.

    flag

    A flag that specifies whether the receiver should process dates entered as expressions in the vernacular (for example, "tomorrow")—YEStrue means that it should.

    Return Value

    An initialized NSDateFormatter instance that uses format in its conversions and that uses the OS X v10.0 formatting behavior.

    Discussion

    NSDateFormatter attempts natural-language processing only after it fails to interpret an entered string according to format. Natural-language processing supports only a limited set of colloquial phrases, primarily in English. It may give unexpected results, and its use is strongly discouraged.

    The following example creates a date formatter with the format string (for example) “Mar 15 1994” and then associates the formatter with the cells of a form (contactsForm):

    1. NSDateFormatter *dateFormat = [[NSDateFormatter alloc]
    2. initWithDateFormat:@"%b %d %Y" allowNaturalLanguage:NO];
    3. [[contactsForm cells] makeObjectsPerformSelector:@selector(setFormatter:)
    4. withObject:dateFormat];

    Special Considerations

    You cannot use this method to initialize a formatter with the OS X v10.4 formatting behavior, you must use init.

    Availability

    Available in OS X v10.4 and later.

    Deprecated in OS X v10.9.

  • The date format string used by the receiver.

    Declaration

    Swift

    var dateFormat: String!

    Objective-C

    @property(copy) NSString *dateFormat

    Discussion

    See Data Formatting Guide for a list of the conversion specifiers permitted in date format strings.

    Availability

    Available in OS X v10.0 and later.

  • The date style of the receiver.

    Declaration

    Swift

    var dateStyle: NSDateFormatterStyle

    Objective-C

    @property NSDateFormatterStyle dateStyle

    Availability

    Available in OS X v10.4 and later.

  • The time style of the receiver.

    Declaration

    Swift

    var timeStyle: NSDateFormatterStyle

    Objective-C

    @property NSDateFormatterStyle timeStyle

    Availability

    Available in OS X v10.4 and later.

  • Returns a localized date format string representing the given date format components arranged appropriately for the specified locale.

    Declaration

    Swift

    class func dateFormatFromTemplate(_ tmplate: String, options opts: Int, locale locale: NSLocale?) -> String?

    Objective-C

    + (NSString *)dateFormatFromTemplate:(NSString *)template options:(NSUInteger)opts locale:(NSLocale *)locale

    Parameters

    template

    A string containing date format patterns (such as “MM” or “h”).

    For full details, see Date and Time Programming Guide.

    opts

    No options are currently defined—pass 0.

    locale

    The locale for which the template is required.

    Return Value

    A localized date format string representing the date format components given in template, arranged appropriately for the locale specified by locale.

    The returned string may not contain exactly those components given in template, but may—for example—have locale-specific adjustments applied.

    Discussion

    Different locales have different conventions for the ordering of date components. You use this method to get an appropriate format string for a given set of components for a specified locale (typically you use the current locale—see currentLocale).

    The following example shows the difference between the date formats for British and American English:

    1. NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    2. NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
    3. NSString *dateFormat;
    4. NSString *dateComponents = @"yMMMMd";
    5. dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:usLocale];
    6. NSLog(@"Date format for %@: %@",
    7. [usLocale displayNameForKey:NSLocaleIdentifier value:[usLocale localeIdentifier]], dateFormat);
    8. dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:gbLocale];
    9. NSLog(@"Date format for %@: %@",
    10. [gbLocale displayNameForKey:NSLocaleIdentifier value:[gbLocale localeIdentifier]], dateFormat);
    11. // Output:
    12. // Date format for English (United States): MMMM d, y
    13. // Date format for English (United Kingdom): d MMMM y

    Availability

    Available in OS X v10.6 and later.

  • The calendar for the receiver.

    Declaration

    Swift

    @NSCopying var calendar: NSCalendar!

    Objective-C

    @property(copy) NSCalendar *calendar

    Availability

    Available in OS X v10.4 and later.

  • The default date for the receiver.

    Declaration

    Swift

    @NSCopying var defaultDate: NSDate?

    Objective-C

    @property(copy) NSDate *defaultDate

    Discussion

    The default default date is nil.

    Availability

    Available in OS X v10.4 and later.

  • The locale for the receiver.

    Declaration

    Swift

    @NSCopying var locale: NSLocale!

    Objective-C

    @property(copy) NSLocale *locale

    Availability

    Available in OS X v10.4 and later.

  • The time zone for the receiver.

    Declaration

    Swift

    @NSCopying var timeZone: NSTimeZone!

    Objective-C

    @property(copy) NSTimeZone *timeZone

    Availability

    Available in OS X v10.4 and later.

  • The earliest date that can be denoted by a two-digit year specifier.

    Declaration

    Swift

    @NSCopying var twoDigitStartDate: NSDate?

    Objective-C

    @property(copy) NSDate *twoDigitStartDate

    Discussion

    If the two-digit start date is set to January 6, 1976, then “January 1, 76” is interpreted as New Year's Day in 2076, whereas “February 14, 76” is interpreted as Valentine's Day in 1976.

    The default date is December 31, 1949.

    Availability

    Available in OS X v10.4 and later.

  • The start date of the Gregorian calendar for the receiver.

    Declaration

    Swift

    @NSCopying var gregorianStartDate: NSDate?

    Objective-C

    @property(copy) NSDate *gregorianStartDate

    Availability

    Available in OS X v10.5 and later.

  • Returns a Boolean value that indicates whether the receiver attempts to process dates entered as a vernacular string.

    Declaration

    Objective-C

    - (BOOL)allowsNaturalLanguage

    Return Value

    YEStrue if the receiver attempts to process dates entered as a vernacular string (“today,” “next week,” “dinner time,” and so on), otherwise NOfalse.

    Discussion

    Natural-language processing supports only a limited set of colloquial phrases, primarily in English. It may give unexpected results, and its use is strongly discouraged.

    Special Considerations

    This method is for use with formatters using NSDateFormatterBehavior10_0 behavior.

    Availability

    Available in OS X v10.4 and later.

    Deprecated in OS X v10.9.

  • A Boolean value that indicates whether the receiver uses heuristics when parsing a string.

    Declaration

    Swift

    var lenient: Bool

    Objective-C

    @property(getter=isLenient) BOOL lenient

    Discussion

    YEStrue if the receiver has been set to use heuristics when parsing a string to guess at the date which is intended, otherwise NOfalse.

    If a formatter is set to be lenient, when parsing a string it uses heuristics to guess at the date which is intended. As with any guessing, it may get the result date wrong (that is, a date other than that which was intended).

    Availability

    Available in OS X v10.10 and later.

  • A Boolean value that indicates whether the receiver uses phrases such as “today” and “tomorrow” for the date component.

    Declaration

    Swift

    var doesRelativeDateFormatting: Bool

    Objective-C

    @property BOOL doesRelativeDateFormatting

    Discussion

    YEStrue if the receiver uses relative date formatting, otherwise NOfalse.

    If a date formatter uses relative date formatting, where possible it replaces the date component of its output with a phrase—such as “today” or “tomorrow”—that indicates a relative date. The available phrases depend on the locale for the date formatter; whereas, for dates in the future, English may only allow “tomorrow,” French may allow “the day after the day after tomorrow,” as illustrated in the following example.

    1. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    2. dateFormatter.timeStyle = NSDateFormatterNoStyle;
    3. dateFormatter.dateStyle = NSDateFormatterMediumStyle;
    4. NSLocale *frLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"];
    5. dateFormatter.locale = frLocale;
    6. dateFormatter.doesRelativeDateFormatting = YES;
    7. NSDate *date = [NSDate dateWithTimeIntervalSinceNow:60*60*24*3];
    8. NSString *dateString = [dateFormatter stringFromDate:date];
    9. NSLog(@"dateString: %@", dateString);
    10. // Output
    11. // dateString: après-après-demain

    Availability

    Available in OS X v10.6 and later.

  • The era symbols for the receiver.

    Declaration

    Swift

    var eraSymbols: [String]!

    Objective-C

    @property(copy) NSArray <NSString *> *eraSymbols

    Discussion

    An array containing NSString objects representing the era symbols for the receiver (for example, {“B.C.E.”, “C.E.”}).

    Availability

    Available in OS X v10.4 and later.

  • The long era symbols for the receiver

    Declaration

    Swift

    var longEraSymbols: [String]!

    Objective-C

    @property(copy) NSArray <NSString *> *longEraSymbols

    Discussion

    An array containing NSString objects representing the era symbols for the receiver (for example, {“Before Common Era”, “Common Era”}).

    Availability

    Available in OS X v10.5 and later.

Data Types

  • The following constants specify predefined format styles for dates and times.

    Declaration

    Swift

    enum NSDateFormatterStyle : UInt { case NoStyle case ShortStyle case MediumStyle case LongStyle case FullStyle }

    Objective-C

    typedef enum { NSDateFormatterNoStyle = kCFDateFormatterNoStyle, NSDateFormatterShortStyle = kCFDateFormatterShortStyle, NSDateFormatterMediumStyle = kCFDateFormatterMediumStyle, NSDateFormatterLongStyle = kCFDateFormatterLongStyle, NSDateFormatterFullStyle = kCFDateFormatterFullStyle } NSDateFormatterStyle;

    Constants

    • NoStyle

      NSDateFormatterNoStyle

      Specifies no style.

      Equal to kCFDateFormatterNoStyle.

      Available in OS X v10.4 and later.

    • ShortStyle

      NSDateFormatterShortStyle

      Specifies a short style, typically numeric only, such as “11/23/37” or “3:30 PM”.

      Equal to kCFDateFormatterShortStyle.

      Available in OS X v10.4 and later.

    • MediumStyle

      NSDateFormatterMediumStyle

      Specifies a medium style, typically with abbreviated text, such as “Nov 23, 1937” or “3:30:32 PM”.

      Equal to kCFDateFormatterMediumStyle.

      Available in OS X v10.4 and later.

    • LongStyle

      NSDateFormatterLongStyle

      Specifies a long style, typically with full text, such as “November 23, 1937” or “3:30:32 PM PST”.

      Equal to kCFDateFormatterLongStyle.

      Available in OS X v10.4 and later.

    • FullStyle

      NSDateFormatterFullStyle

      Specifies a full style with complete details, such as “Tuesday, April 12, 1952 AD” or “3:30:42 PM Pacific Standard Time”.

      Equal to kCFDateFormatterFullStyle.

      Available in OS X v10.4 and later.

    Discussion

    The format for these date and time styles is not exact because they depend on the locale, user preference settings, and the operating system version. Do not use these constants if you want an exact format.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.4 and later.

  • Constants that specify the behavior NSDateFormatter should exhibit.

    Declaration

    Swift

    enum NSDateFormatterBehavior : UInt { case BehaviorDefault case Behavior10_0 case Behavior10_4 }

    Objective-C

    typedef enum { NSDateFormatterBehaviorDefault = 0, NSDateFormatterBehavior10_0 = 1000, NSDateFormatterBehavior10_4 = 1040, } NSDateFormatterBehavior;

    Constants

    • BehaviorDefault

      NSDateFormatterBehaviorDefault

      Specifies default formatting behavior.

      Available in OS X v10.4 and later.

    • Behavior10_0

      NSDateFormatterBehavior10_0

      Specifies formatting behavior equivalent to that in OS X v10.0.

      Available in OS X v10.4 and later.

    • Behavior10_4

      NSDateFormatterBehavior10_4

      Specifies formatting behavior equivalent for OS X v10.4.

      Available in OS X v10.4 and later.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.4 and later.