当前位置: 代码迷 >> 综合 >> 20200714--iOS之DateFormatter类,日期格式化器
  详细解决方案

20200714--iOS之DateFormatter类,日期格式化器

热度:70   发布时间:2024-01-28 01:29:19.0

Class

DateFormatter

A formatter that converts between dates and their textual representations.

--在日期及其文本表示形式之间进行转换的格式化程序。将date作为formatter的参数进行格式化输出

 

Declaration         --声明

class DateFormatter : Formatter

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.

--DateFormatter的实例创建NSDate对象的字符串表示,并将日期和时间的文本表示转换NSDate对象。对于用户可见的日期和时间表示,DateFormatter提供了各种本地化预置和配置选项。对于日期和时间的固定格式表示,可以指定自定义格式字符串。

 

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

--使用ISO8601格式的日期表示时,请使用ISO8601DateFormatter。

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

--要表示两个NSDate对象之间的间隔,请使用DateIntervalFormatter代替

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

--要表示NSDateComponents对象指定的时间量,请使用DateComponentsFormatter。

 

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.

--在向用户显示日期时,可以根据您的具体需要设置 date formatter 的dateStyletimeStyle属性。例如,如果您想要显示月份、日期和年份而不显示时间,则可以将dateStyle属性设置为DateFormatter.Style.long 并且将timeStyle属性设置为DateFormatter. Style.none 。相反,如果您只想显示时间,您可以将dateStyle属性设置为DateFormatter.Style.none 并且将timeStyle属性设置为DateFormatter.Style.short。DateFormatter根据dateStyle和timeStyle属性的值,提供适合于给定语言环境的指定日期的表示。


let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .nonelet date = Date(timeIntervalSinceReferenceDate: 118800)// US English Locale (en_US)
dateFormatter.locale = Locale(identifier: "en_US")
print(dateFormatter.string(from: date)) // Jan 2, 2001// French Locale (fr_FR)
dateFormatter.locale = Locale(identifier: "fr_FR")
print(dateFormatter.string(from: date)) // 2 janv. 2001// Japanese Locale (ja_JP)
dateFormatter.locale = Locale(identifier: "ja_JP")
print(dateFormatter.string(from: date)) // 2001/01/02

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.

--如果需要定义使用预定义样式无法实现的格式,可以使用setLocalizedDataFormatFromTemplate(:)方法从模板中指定本地化的日期格式。


let dateFormatter = DateFormatter()
let date = Date(timeIntervalSinceReferenceDate: 410220000)// US English Locale (en_US)
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.setLocalizedDateFormatFromTemplate("MMMMd") // set template after setting locale
print(dateFormatter.string(from: date)) // December 31// British English Locale (en_GB)
dateFormatter.locale = Locale(identifier: "en_GB")
dateFormatter.setLocalizedDateFormatFromTemplate("MMMMd") // // set template after setting locale
print(dateFormatter.string(from: date)) // 31 December

Working With Fixed Format Date Representations         --使用固定格式的日期表示

Important

In macOS 10.12 and later or iOS 10 and later, use the ISO8601DateFormatter class when working with ISO 8601 date representations.

--在macOS 10.12及以后版本或ios10及以后版本中,使用iso8601日期表示时使用ISO8601DateFormatter类。

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.

--在处理固定格式的日期(比如RFC 3339)时,可以设置dateFormat属性来指定格式字符串。对于大多数固定格式,您还应该将locale属性设置为POSIX locale(“en US POSIX”),并将时区属性设置为UTC。


let RFC3339DateFormatter = DateFormatter()
RFC3339DateFormatter.locale = Locale(identifier: "en_US_POSIX")
RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
RFC3339DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)/* 39 minutes and 57 seconds after the 16th hour of December 19th, 1996 with an offset of -08:00 from UTC (Pacific Standard Time) */
let string = "1996-12-19T16:39:57-08:00"
let date = RFC3339DateFormatter.date(from: string)

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

 

Thread Safety            --线程安全

On iOS 7 and later NSDateFormatter is thread safe.

--ios7和以后的NSDateFormatter是线程安全的。

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

--在MacOS10.9和更高版本中,只要您在64位应用程序中使用现代行为,NSDateFormatter就是线程安全的。

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.

--在操作系统的早期版本上,或者在使用遗留格式化程序行为时,或者在macOS中运行32位格式程序时,NSDateFormatter不是线程安全的,因此不能同时从多个线程修改日期格式化程序。

 

Topics             --专题

Converting Objects            --转换对象

func date(from: String) -> Date?

Returns a date representation of a given string interpreted using the receiver’s current settings.

func string(from: Date) -> String

Returns a string representation of a given date formatted using the receiver’s current settings.

class func localizedString(from: Date, dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> String

Returns a string representation of a given date, formatted for the current locale using the specified date and time styles.

func getObjectValue(AutoreleasingUnsafeMutablePointer<AnyObject?>?, for: String, range: UnsafeMutablePointer<NSRange>?)

Returns by reference a date representation of a given string and the range of the string used, and returns a Boolean value that indicates whether the string could be parsed.

 

Managing Formats and Styles              --管理格式和样式

var dateStyle: DateFormatter.Style

The date style of the receiver.

var timeStyle: DateFormatter.Style

The time style of the receiver.

var dateFormat: String!

The date format string used by the receiver.

func setLocalizedDateFormatFromTemplate(String)

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

class func dateFormat(fromTemplate: String, options: Int, locale: Locale?) -> String?

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

var formattingContext: Formatter.Context

The capitalization formatting context used when formatting a date.

 

Managing Attributes           --管理属性

var calendar: Calendar!

The calendar for the receiver.

var defaultDate: Date?

The default date for the receiver.

var locale: Locale!

The locale for the receiver.

var timeZone: TimeZone!

The time zone for the receiver.

var twoDigitStartDate: Date?

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

var gregorianStartDate: Date?

The start date of the Gregorian calendar for the receiver.

 

Managing Behavior Version             --管理行为版本

var formatterBehavior: DateFormatter.Behavior

The formatter behavior for the receiver.

class var defaultFormatterBehavior: DateFormatter.Behavior

Returns the default formatting behavior for instances of the class.

Managing Natural Language Support              --管理自然语言的支持

var isLenient: Bool

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

var doesRelativeDateFormatting: Bool

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

 

Managing AM and PM Symbols         --管理AM和PM字符

var amSymbol: String!

The AM symbol for the receiver.

var pmSymbol: String!

The PM symbol for the receiver.

 

Managing Weekday Symbols            --管理星期的表示

var weekdaySymbols: [String]!

The array of weekday symbols for the receiver.

var shortWeekdaySymbols: [String]!

The array of short weekday symbols for the receiver.

var veryShortWeekdaySymbols: [String]!

The array of very short weekday symbols for the receiver.

var standaloneWeekdaySymbols: [String]!

The array of standalone weekday symbols for the receiver.

var shortStandaloneWeekdaySymbols: [String]!

The array of short standalone weekday symbols for the receiver.

var veryShortStandaloneWeekdaySymbols: [String]!

The array of very short standalone weekday symbols for the receiver.

 

Managing Month Symbols         --管理月的表示

var monthSymbols: [String]!

The month symbols for the receiver.

var shortMonthSymbols: [String]!

The array of short month symbols for the receiver.

var veryShortMonthSymbols: [String]!

The very short month symbols for the receiver.

var standaloneMonthSymbols: [String]!

The standalone month symbols for the receiver.

var shortStandaloneMonthSymbols: [String]!

The short standalone month symbols for the receiver.

var veryShortStandaloneMonthSymbols: [String]!

The very short month symbols for the receiver.

 

Managing Quarter Symbols          --管理季度的表示

var quarterSymbols: [String]!

The quarter symbols for the receiver.

var shortQuarterSymbols: [String]!

The short quarter symbols for the receiver.

var standaloneQuarterSymbols: [String]!

The standalone quarter symbols for the receiver.

var shortStandaloneQuarterSymbols: [String]!

The short standalone quarter symbols for the receiver.

 

Managing Era Symbols          --管理纪元的表示

var eraSymbols: [String]!

The era symbols for the receiver.

var longEraSymbols: [String]!

The long era symbols for the receiver

 

Constants           --常量

enum DateFormatter.Style

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

enum DateFormatter.Behavior

Constants that specify the behavior NSDateFormatter should exhibit.

 

Instance Properties           --实例属性

var generatesCalendarDates: Bool

Indicates whether the formatter generates the deprecated calendar date type.

 

Relationships         --继承关系

Inherits From

  • Formatter

Conforms To

  • CVarArg
  • Equatable
  • Hashable

See Also

Date Formatting

class DateComponentsFormatter

A formatter that creates string representations of quantities of time.

class DateIntervalFormatter

A formatter that creates string representations of time intervals.

class ISO8601DateFormatter

A formatter that converts between dates and their ISO 8601 string representations.