IOS Date Processing (Swift3.0 NSDate), swift3.0nsdate

Source: Internet
Author: User
Tags date1 time zones what date

IOS Date Processing (Swift3.0 NSDate), swift3.0nsdate
Common scenarios for Processing Dates

  1. NSDate-> String & String-> NSDate

  2. Date comparison

  3. Date calculation (based on reference date +/-a certain time)

  4. Differences during computing days

  5. Disassemble the NSDate object (into year/month/day/hour/minute/second, etc)

NSDate-related classes
  1. NSDate

  2. DateFormatter

  3. DateComponents

  4. DateComponentFormatter

  5. Calendar

  6. Date structure: Date structure is introduced in Swift3.0, which is similar to the functions provided by NSDate. In addition, the Date struct and NSDate classes can be used in Swift to interact with Objective-C APIs. the introduction of the Date struct is the same as that of the String and Array types introduced in Swift to bridge the corresponding classes in the Foundation (String-> NSString, Array-> NSArray)

Note: In the following code snippets, The NSDate and Date functions are the same.

Basic Concepts
  • Before writing code, it is necessary to clarify some basic concepts:

    • NSDate object: It can describe the date and time at the same time. It will be used when processing the date or time.

    • DateFormatter object: A format object is useful only when NSDate and String are converted to each other. It is used to specify the format. this includes the built-in format and manual custom format, and supports time zone settings.

    • DateComponents class: it can be seen as the sister class of NSDate. it provides many practical features and operations. one of the most important features is that it can split the date or time, that is, every part of the date or time (such as year, month, day, hour, minute, etc) can be obtained separately and other operations (such as computing) can be performed ).

    • DateComponentsFormatter class: Used to output the date and time that the computer reads to a human-readable string.

    • Calendar class: Date class can convert between NSDate and DateComponents.

Conversion between NSDate and String
  • Obtain the current date and time

let currentDate = Date ()
print (currentDate) // 2016-08-19 05:33:48 +0000 Greenwich Mean Time

Initialize the DateFormatter class

let dateFormatter = DateFormatter ()
dateFormatter.locale = Locale.current () // Set the time zone

Use the system's own style to output the date

Before converting an NSDate object to a String type, you first need to tell the computer what date format you want to output. There are two ways. The first is to use the system's own format, and the second method is to manually use specific instructions. To specify the output format. Here first look at the output of the system's own format.

dateFormatter.dateStyle = DateFormatter.Style.noStyle
var stringDate = dateFormatter.string (from: currentDate)
print (stringDate) // "No output"
dateFormatter.dateStyle = DateFormatter.Style.shortStyle
stringDate = dateFormatter.string (from: currentDate)
print (stringDate) // 8/19/16
dateFormatter.dateStyle = DateFormatter.Style.mediumStyle
stringDate = dateFormatter.string (from: currentDate)
print (stringDate) // Aug 19, 2016
dateFormatter.dateStyle = DateFormatter.Style.longStyle
stringDate = dateFormatter.string (from: currentDate)
print (stringDate) // August 19, 2016
dateFormatter.dateStyle = DateFormatter.Style.fullStyle
stringDate = dateFormatter.string (from: currentDate)
print (stringDate) // Friday, August 19, 2016

Output date using custom specifier

EEEE: represents the full name of the day, such as Monday. Use 1-3 E to represent the abbreviation, such as Mon.

MMMM: Represents the full name of a month, such as July. Use 1-3 M to represent shorthand, such as Jul.

dd: Represents the day of the month, such as 07 or 30.

yyyy: represents the year represented by 4 numbers, such as 2016.

HH: Represents the hour indicated by 2 numbers, such as 08 or 17.

mm: represents the minute represented by 2 numbers, such as 01 or 59.

ss: represents the seconds represented by 2 numbers, such as 2016.

zzz: represents the time zone represented by 3 letters, such as GTM (Greenwich Mean Time, GMT + 8 is the time zone where Beijing is located, commonly known as East Eight District)

GGG: BC or AD, ie BC or AD

When the style that comes with the system is not enough, you can use a custom specifier to customize the output format of Date.

Another huge effect of the custom specifier is that it can convert the date format of complex character types (such as Fri, 08 Aug 2016 09:22:33 GMT) to Date type.

The most important use of custom formats is the use of custom specifiers. Specifiers are simple characters that have a characteristic meaning for date objects. The following first lists some specifiers that will be used here:

For the specific introduction of specifiers, please refer to the official documentation

Let's continue to look at the actual use of custom specifiers. The following will convert the current date to a string type, and output the full name of the week and month. The year and days are represented by numbers:

dateFormatter.dateFormat = "EEEE, MMMM, dd, yyyy"
stringDate = dateFormatter.string (from: currentDate)
print (stringDate) // Friday, August, 19, 2016

It can be intuitively seen from the example that the technology of customizing the output format is actually very simple. The specific output format depends on the specific needs. Finally, let me give an example (output format-> hour: minute: second week short month display Digital days display digital time zone AD):

dateFormatter.dateFormat = "HH: mm: ss E M dd zzz GGG"
stringDate = dateFormatter.string (from: currentDate)
print (stringDate) // 14:20:31 Fri 8 19 GMT + 8 AD

The above examples are all Date to String, the reverse conversion of this conversion process is more interesting. The output format and custom specifiers used in the system used before are also applicable in the process of String to Date. The most important in the process of String to Date The point is to set the appropriate format corresponding to String, otherwise the output will be nil.

var dateString = "2016-12-02 18:15:59"
dateFormatter.dateFormat = "yyyy-MM-dd HH: mm: ss"
print ( (from: dateString)) // 2016-12-02 10:15:59 +0000

It should be noted here that the time of the string is 18:15:59, and the time of the output is 10:15:59. The reason is because the time zone I am in is the time zone of Beijing, which is the East Eight District, and the default output is Greenwich Mean Time is output, which is 8 hours apart.

Here is a more complex example, including the output of the time zone:

dateString = "Mon, 08, Aug 2008 20:00:01 GMT"
dateFormatter.dateFormat = "E, dd, MM yyyy HH: mm: ss zzz"
dateFromString = (from: dateString)
print (dateFromString) // 2008-08-08 20:00:01 +0000

In many scenarios, you may need to disassemble the value of the date, and then extract the specific value. For example, you may need to get the value of days and months in a date, or get the value of hours and minutes from time The DateComponents class will be introduced to solve this problem. It should be noted that the DateComponents class will often be used with Calendar. Specifically, the Calendar class method is to achieve the conversion of Date to DateComponents, and the reverse conversion. Remember After this point, first get the currentCalendar object, and assign it to a constant for later use.

let calendar = Calendar.current ()

The following code demonstrates the process of Date-> DateComponents through a typical example.

let dateComponents = calendar.components ([Calendar.Unit.era, Calendar.Unit.year, Calendar.Unit.month,, Calendar.Unit.hour, Calendar.Unit.minute, Calendar.Unit.second] , from: currentDate)
print ("era: (dateComponents.era) year: (dateComponents.year) month: (dateComponents.month) day: ( hour: (dateComponents.hour) minute: (dateComponents.minute) second: (dateComponents. second) ")
// era: Optional (1) year: Optional (2016) month: Optional (8) day: Optional (19) hour: Optional (15) minute: Optional (29) second: Optional (13)

The components (_: from :) method in the Calendar class is used above. This method receives two parameters. The second parameter is the date object to be disassembled. The first parameter is more interesting. This parameter is a Array, put in each component unit (Calendar.Unit) that makes up the date, such as month (Calendar.Unit.month), day (

Calendar.Unit is a structure, and all the attributes and descriptions in it can be viewed in the official documentation.

It should also be noted that in the first array parameter of the components (_: from :) method, if the unit name you want to resolve is not passed in, then the unit will not be available from the DateComponents object, such as the above There is no Calendar.Unit.month passed in the method, then if the value is also printed when the last printing, the value obtained will be nil.

dateComponents = calendar.components ([Calendar.Unit.year], from: currentDate)
print ("year: (dateComponents.year) month: (dateComponents.month)")
// Optional (2016) month: nil

DateComponents-> Date

Conversion of DateComponents-> Date is also very simple, just initialize a DateComponents object, then specify specific components, and finally call the dateFromComponents: method of the Calendar class to complete the conversion

var components = DateComponents ()
components.year = 1985
components.month = 02 = 05
components.hour = 07
components.minute = 08
components.second = 44
let dateFromComponents = (from: components)
print (dateFromComponents) // Optional (1985-02-04 23:08:44 +0000)

Here you can also set different time zones to get the local time:

components.timeZone = TimeZone (abbreviation: "GMT") // Greenwich Mean Time
components.timeZone = TimeZone (abbreviation: "CST") // China Standard Time
components.timeZone = TimeZone (abbreviation: "CET") // Central European Time

Compare date and time
In addition to the application scenarios mentioned above, another common application scenario for dates and times is comparison. By comparing two Date objects to determine which date is earlier or later, or whether the date is the same. Here will be introduced There are 3 ways to compare, the method is good or bad, the most important is to suit your needs.

Before starting the comparison, first create two Date objects for the following comparison:

dateFormatter.dateFormat = "MMM dd, yyyy zzz"
dateString = "May 08, 2016 GMT"
var date1 = (from: dateString)
dateString = "May 10, 2016 GMT"
var date2 = (from: dateString)
print ("date1: (date1) ---- date2: (date2)")
// date1: Optional (2016-05-08 00:00:00 +0000)
// date2: Optional (2016-05-10 00:00:00 +0000)

Method 1 (earlierDate: || laterDate :)
When comparing the dates of date1 and date2 which is earlier or later, use the earlierDate: and laterDate: methods provided by the NSDate class.

print ((date1! as NSDate) .earlierDate (date2!)) // 2016-05-08 00:00:00 +0000
print ((date1! as NSDate) .laterDate (date2!)) // 2016-05-10 00:00:00 +0000

When using the earlierDate: method, the return value is an NSDate object with an earlier date; the return value for laterDate: is an NSDate object with a later date.

In the above method, because date1 and date2 belong to the Date class, and the earlierDate: and laterDate: methods want to receive the parameter type is NSDate, so the type conversion is performed first.

Method 2 (compare:)
The second method of comparison is to use the compare: method provided by the Date structure, and the return value is an enumeration of ComparisonResult type.

if date1? .compare (date2!) == ComparisonResult.orderedAscending {
    print ("date1 is earlier")
} else if date1? .compare (date2!) == ComparisonResult.orderedDescending {
    print ("date2 is earlier")
} else if date1? .compare (date2!) == ComparisonResult.orderedSame {
    print ("Same date !!!")

Method 3 (timeIntervalSinceReferenceDate)
The third method is a bit different. The principle is to compare date1 and date2 with a reference date, and then judge the difference between the two dates by judging the difference between the two dates and the reference date.

To give an example: compare the two numbers 4 and 10, first select 6 as a reference number, 4-6 = -2; 10-6 = 4, 4-(-2) = 6.

if date1? .timeIntervalSinceReferenceDate> date2? .timeIntervalSinceReferenceDate {
    print ("date1 is later")
} else if date1? .timeIntervalSinceReferenceDate <date2? .timeIntervalSinceReferenceDate {
    print ("date2 is later")
} else if date1? .timeIntervalSinceReferenceDate == date2? .timeIntervalSinceReferenceDate {
    print ("Same Date")

Calculation of the date
Another interesting scenario for dealing with dates is the calculation of dates. For example, the calculation of 2016-08-12 plus 2 months and 12 days and so on. Here we will introduce two different methods for date calculation. The first one The method uses the CalendarUnit structure of the Calendar class; the second method uses the DateComponents class.

First remember the current date:

print (NSDate ()) // 2016-08-19 08:29:12 +0000

The following assumes that you want to calculate the current date plus 2 months and 5 days

let monthsToAdd = 2
let daysToAdd = 5

method 1
var calculatedDate = (byAdding: Calendar.Unit.month, value: monthsToAdd, to: currentDate, options: Calendar.Options.init (rawValue: 0))
calculatedDate = (byAdding:, value: daysToAdd, to: calculatedDate !, options: Calendar.Options.init (rawValue: 0))
print (calculatedDate) // Optional (2016-10-24 08:33:41 +0000)

As shown in the code above, the dateByAddingUnit: value: toDate: options: method is used here. This method adds a specific date unit value to an existing date value, and then returns a new Date object. Because the example here is Two values are added, so this method needs to be called twice.

Method 2
Although method 1 is feasible, it has the disadvantage that each unit calculation needs to call the method separately. If you want to add 7 years, 3 months, 4 days, 8 hours, 23 minutes and 34 seconds to the current date, then you must call dateByAddingUnit: value: toDate: options: Method 6 times! And Method 2 can solve this problem. Method 2 once used the DateComponents class.

Next, I will first initialize a new DateComponents object, then set the month and days, and then call the method named dateByAddingComponents: toDate: options: in the Calendar class.The return value of this method is the calculated Date object.

var newDateComponents = DateComponents ()
newDateComponents.month = 2 = 5
calculatedDate = (byAdding: newDateComponents, to: currentDate, options: Calendar.Options.init (rawValue: 0))
print (calculatedDate) // Optional (2016-10-24 08:47:57 +0000)

Calculation of date difference
Calculating the specific difference between two days is also a problem that is often encountered when dealing with date objects. Here are 3 methods to solve this problem.

First, first customize two date objects:

dateFormatter.dateFormat = "yyyy-MM-dd HH: mm: ss"
dateString = "2016-08-08 18:25:17"
date1 = (from: dateString)
dateString = "1985-02-05 07:45:38"
date2 = (from: dateString)

method 1
Method 1 uses an object method components: from: to: options: in the Calendar class.

var diffComponents = calendar.components ([Calendar.Unit.year, Calendar.Unit.month,], from: date2 !, to: date1 !, options: Calendar.Options.init (rawValue: 0))
print ("date1 and date2 are different in (diffComponents.year) years (diffComponents.month) months and (diffComponents.year) days")
// date1 and date2 are different in Optional (31) years Optional (6) months and Optional (31) days

The first parameter in the components: from: to: options: method still receives an array containing the Calendar.Unit structure. Because it is from date2 to date1, the return value in ascending order is a positive number. The value is negative.

Method 2
The second method introduced here will use the DateComponentsFormatter class for the first time. The DateComponentsFormatter class provides many different methods for automatic calculation during the day, and the return value is a formatted string.

Initialize a DateComponentsFormatter object first, and then specify one of its attribute values.

let dateComponentsFormatter = DateComponentsFormatter ()
dateComponentsFormatter.unitsStyle = DateComponentsFormatter.UnitsStyle.full

let interval = date2? .timeIntervalSince (date1!)
var diffString = dateComponentsFormatter.string (from: interval!)
print (diffString) // Optional ("-31 years, 6 months, 0 weeks, 3 days, 10 hours, 39 minutes, 39 seconds")

The UnitsStyle property will specify the format of the final result output. Full is used here, which means that the output unit will be displayed in full name, such as Monday, June, etc. If you want to use shorthand, you can reset the property. The official document lists all The attribute value.

Method 3
dateComponentsFormatter.allowedUnits = [Calendar.Unit.year]
diffString = dateComponentsFormatter.string (from: date1 !, to: date2!)
print (diffString) // Optional ("-31 years")

The last method calls the stringFrom: to: method to calculate. Note that before using this method, at least one calendar unit must be set in the allowedUnits property, otherwise this method will return nil, so before using this method, first specify how you want See the output in this way, and then let the method perform the output.

to sum up
As I said in the summary, dealing with dates is very common and inevitable in everyday code. Here I introduce some common methods of dealing with dates through some small code snippets. Whether it is NSDate class, Date structure or the same Related classes have only one purpose, which is to be able to process dates quickly. If you want to master the processing of dates, you still need to practice more in the daily coding process and read more official documents.


Learning collection,

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.