Contents

DateFormatter

A formatter that converts between dates and their textual representations.

Declaration

class DateFormatter

Overview

Instances of DateFormatter 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, DateFormatter provides a variety of localized presets and configuration options. For fixed format representations of dates and times, you can specify a custom format string.

When working with date representations in ISO 8601 format, use ISO8601DateFormatter instead.

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

To represent a quantity of time specified by an NSDateComponents object, use DateComponentsFormatter 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 DateFormatter.Style.long and the timeStyle property to DateFormatter.Style.none. Conversely, if you want to show only the time, you would set the dateStyle property to DateFormatter.Style.none and the timeStyle property to DateFormatter.Style.short. Based on the values of the dateStyle and timeStyle properties, DateFormatter provides a representation of a specified date that is appropriate for a given locale.

If you need to define a format that cannot be achieved using the predefined styles, you can use the setLocalizedDateFormatFromTemplate(_:) to specify a localized date format from a template.

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.

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

Thread Safety

On iOS 7 and later NSDateFormatter is thread safe.

In macOS 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 in macOS, NSDateFormatter is not thread safe, and you therefore must not mutate a date formatter simultaneously from multiple threads.

Topics

Converting Objects

Managing Formats and Styles

Managing Attributes

Managing Behavior Version

Managing Natural Language Support

Managing AM and PM Symbols

Managing Weekday Symbols

Managing Month Symbols

Managing Quarter Symbols

Managing Era Symbols

Deprecated

Constants

See Also

Dates and times