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. For user-visible representations of dates and times, NSDateFormatter provides a variety of localized presets and configuration options. For fixed format representations of dates and times, such as RFC 3339, you can specify a custom format string.

To represent an interval between two NSDate objects, use NSDateIntervalFormatter instead.

To represent a quantity of time specified by an NSDateComponents object, use NSDateComponentsFormatter instead.

Working With User-Visible Representations of Dates and Times

When displaying a date to a user, you set the dateStyle and timeStyle properties of the date formatter according to your particular needs. For example, if you want to show the month, day, and year without showing the time, you would set the dateStyle property to NSDateFormatterLongStyle and the timeStyle property to NSDateFormatterNoStyle. Conversely, if you want to show only the time, you would set the dateStyle property to NSDateFormatterNoStyle and the timeStyle property to NSDateFormatterShortStyle. Based on the values of the dateStyle and timeStyle properties, NSDateFormatter provides a representation of a specified date that is appropriate for a given locale.

Objective-C

  1. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  2. dateFormatter.dateStyle = NSDateFormatterMediumStyle;
  3. dateFormatter.timeStyle = NSDateFormatterNoStyle;
  4. NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:118800];
  5. // US English Locale (en_US)
  6. dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
  7. NSLog(@"%@", [dateFormatter stringFromDate:date]); // Jan 2, 2001
  8. // French Locale (fr_FR)
  9. dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"];
  10. NSLog(@"%@", [dateFormatter stringFromDate:date]); // 2 janv. 2001
  11. // Japanese Locale (ja_JP)
  12. dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"ja_JP"];
  13. NSLog(@"%@", [dateFormatter stringFromDate:date]); // 2001/01/02

Swift

  1. let dateFormatter = NSDateFormatter()
  2. dateFormatter.dateStyle = .MediumStyle
  3. dateFormatter.timeStyle = .NoStyle
  4. let date = NSDate(timeIntervalSinceReferenceDate: 118800)
  5. // US English Locale (en_US)
  6. dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
  7. NSLog("%@", dateFormatter.stringFromDate(date)) // Jan 2, 2001
  8. // French Locale (fr_FR)
  9. dateFormatter.locale = NSLocale(localeIdentifier: "fr_FR")
  10. NSLog("%@", dateFormatter.stringFromDate(date)) // 2 janv. 2001
  11. // Japanese Locale (ja_JP)
  12. dateFormatter.locale = NSLocale(localeIdentifier: "ja_JP")
  13. NSLog("%@", dateFormatter.stringFromDate(date)) // 2001/01/02

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.

Working With Fixed Format Date Representations

When working with fixed format dates, such as RFC 3339, you set the dateFormat property to specify a format string. For most fixed formats, you should also set the locale property to a POSIX locale ("en_US_POSIX"), and set the timeZone property to UTC.

Objective-C

  1. RFC3339DateFormatter = [[NSDateFormatter alloc] init];
  2. RFC3339DateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  3. RFC3339DateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZZZZZ";
  4. RFC3339DateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
  5. /* 39 minutes and 57 seconds after the 16th hour of December 19th, 1996 with an offset of -08:00 from UTC (Pacific Standard Time) */
  6. NSString *string = @"1996-12-19T16:39:57-08:00";
  7. NSDate *date = [RFC3339DateFormatter dateFromString:string];

Swift

  1. let RFC3339DateFormatter = NSDateFormatter()
  2. RFC3339DateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
  3. RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
  4. RFC3339DateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
  5. /* 39 minutes and 57 seconds after the 16th hour of December 19th, 1996 with an offset of -08:00 from UTC (Pacific Standard Time) */
  6. let string = "1996-12-19T16:39:57-08:00"
  7. let date = RFC3339DateFormatter.dateFromString(string)

For more information, see Technical Q&A QA1480 “NSDateFormatter and Internet Dates”.

Formatter Behaviors

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

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

Thread Safety

On iOS 7 and later NSDateFormatter is thread safe.

On OS X 10.9 and later NSDateFormatter is thread safe so long as you are using the modern behavior in a 64-bit app.

On earlier versions of the operating system, or when using the legacy formatter behavior or running in 32-bit on OS X, NSDateFormatter is not thread safe, and you therefore must not mutate a date formatter simultaneously from multiple threads.

  • Initializes and returns an NSDateFormatter instance that uses the OS X 10.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 10.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 10.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:

    Objective-C

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

    Swift

    1. let usLocale = NSLocale(localeIdentifier: "en_US")
    2. let gbLocale = NSLocale(localeIdentifier: "en_GB")
    3. let template = "yMMMMd"
    4. let usDateFormat = NSDateFormatter.dateFormatFromTemplate(template, options: 0, locale: usLocale)!
    5. // Date format for English (United States): "MMMM d, y"
    6. let gbDateFormat = NSDateFormatter.dateFormatFromTemplate(template, options: 0, locale: gbLocale)!
    7. // Date format for English (United Kingdom): "d MMMM y"

    Availability

    Available in OS X v10.6 and later.

  • Sets the date format from a template using the specified locale for the receiver.

    Declaration

    Swift

    func setLocalizedDateFormatFromTemplate(_ dateFormatTemplate: String)

    Objective-C

    - (void)setLocalizedDateFormatFromTemplate:(NSString *)dateFormatTemplate

    Parameters

    dateFormatTemplate

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

    For full details, see Date and Time Programming Guide.

    Discussion

    Calling this method is equivalent to, but not necessarily implemented as, setting the dateFormat property to the result of calling the dateFormatFromTemplate:options:locale: method, passing no options and the locale property value.

    Availability

    Available in OS X v10.10 and later.

  • The calendar for the receiver.

    Declaration

    Swift

    @NSCopying var calendar: NSCalendar!

    Objective-C

    @property(copy) NSCalendar *calendar

    Discussion

    If unspecified, the logical calendar for the current user is used.

    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

    By default, this property 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

    Discussion

    If unspecified, the system time zone is used.

    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.

    By default, this property is equal to 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

    Discussion

    This is used to specify the start date for the Gregorian calendar switch from the Julian calendar. Different locales switched at different times. Normally you should just accept the locale's default date for the switch.

    See NSCalendar for more information.

    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.4 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 10.0.

      Available in OS X v10.4 and later.

    • Behavior10_4

      NSDateFormatterBehavior10_4

      Specifies formatting behavior equivalent for OS X 10.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.