Guidelines on the use of date classes in Swift3.0

Source: Internet
Author: User
Tags date1 dateformat time zones locale set time what date

common scenarios for working with dates
    1. NSDate, String & string-NSDate

    2. Date comparison

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

    4. Calculate the difference during the day

    5. Disassembling nsdate objects (decomposed into year/month/day/hour/minute/second, etc.)

NSDate Related Classes
    1. NSDate

    2. Dateformatter

    3. Datecomponents

    4. Datecomponentformatter

    5. Calendar

    6. Date structure is introduced in date structure:swift3.0, similar to the functionality provided by NSDate, and the date struct and NSDate classes can be used interchangeably in swift to achieve and Objective-c APIs. The introduction of the date struct and the introduction of the string, array, and so on in Swift are all for the corresponding class bridging the corresponding class in the foundation (string, NSString, array, Nsarray)

Note: In the following code snippet, NSDate and date are used interchangeably and the functionality is the same.

Basic Concepts
    • Before you start writing code, it is necessary to understand some of the basic concepts:

      • NSDate object: The date and time can be described and used when the date or time is to be processed.

      • Dateformatter object: A Format object is valuable only when it converts nsdate and string to each other, and it is used to specify the format. This includes the format that comes with the system and the manual custom format, which also supports the settings for the time zone.

      • Datecomponents class: Can be regarded as the sister class of NSDate. Because it provides a lot of practical features and operations. One of the most important features is that it can be separated by a date or time, that is, every part of the date or time (such as year, month, day, hour, minute, etc.) can be taken out separately, and other operations (such as calculation).

      • Datecomponentsformatter class: The date and time used to read a computer into a human-readable string.

      • Calendar class: The date class can implement conversions between NSDate and datecomponents.

conversion between NSDate and string
  • Get the current date and time

    Let currentdate = Date () print (currentdate)//2016-08-19 05:33:48 +0000 GMT
  • Initialize the Dateformatter class

    Let Dateformatter = Dateformatter () Dateformatter.locale = Locale.current ()//Set time zone
  • Output date using the system's own style

    • Before you convert a NSDate object to a string type, you first need to tell the computer what date format you want to output. There are two ways of doing this. The first is to use the system's own format, and the second method is to manually specify the output format with a specific specifier. Here, let's look at the output of the system's own format.

      dateformatter.datestyle = dateformatter.style.nostylevar  Stringdate = dateformatter.string (from: currentdate) print (stringdate)  //  "No output" Dateformatter.datestyle = dateformatter.style.shortstylestringdate = dateformatter.string ( from: currentdate) print (stringdate)  // 8/19/16dateFormatter.dateStyle =  Dateformatter.style.mediumstylestringdate = dateformatter.string (from: currentdate) print ( StringDate)  // Aug 19, 2016dateFormatter.dateStyle =  Dateformatter.style.longstylestringdate = dateformatter.string (from: currentdate) print ( StringDate)  // August 19, 2016dateFormatter.dateStyle =  Dateformatter.style.fullstylestringdate = dateformatter.string (from: currentdate) print ( StringDate)  // friday, august 19, 2016 
  • Output date using custom specifiers

    • Eeee: Represents the full name of a day, such as Monday. Use 1-3 e to represent shorthand, such as Mon.

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

    • DD: Represents the number of one months, such as 07 or 30.

    • YYYY: Represents a 4-digit year, such as 2016.

    • HH: An hour representing 2 digits, such as 08 or 17.

    • MM: Represents a 2-digit minute, such as 01 or 59.

    • SS: Represents the second of 2 digits, such as 2016.

    • ZZZ: Represents a 3-letter time zone, such as GTM (Greenwich Mean Time, Gmt+8 is Beijing's time zone, commonly known as the East Eight zone)

    • GGG:BC or ad, i.e. BC or A.D.

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

    • Another huge function of custom specifiers is the ability to convert date formats of complex character types (such as Fri, 09:22:33 GMT) to date types.

    • The most important use of custom formats is the use of custom specifiers, which are simple characters that have a characteristic meaning to the Date object. Here are some of the specifiers that will be used here:

    • For a specific description of the specifier, please refer to the official documentation

    • Continue to look at the actual use of the custom specifier, which converts the current date to a string type, and outputs the full name of the week and month, the year and the number of days in numbers:

      Dateformatter.dateformat = "Eeee, MMMM, DD, yyyy" stringdate = dateformatter.string (from:currentdate) print (stringdate) Friday, August, 19, 2016
    • From the example can be very intuitive to see the fact that the custom output format of the technology is very simple, the specific output format depends on the specific needs, and finally another example ( output format - hour: minutes: Seconds Weekday Month display number of days display digital time zone A.D. ) :

      Dateformatter.dateformat = "HH:mm:ss E M dd zzz GGG" stringdate = dateformatter.string (from:currentdate) print (stringdate )//14:20:31 Fri 8 gmt+8 AD
  • The above examples are all date-to-string, and the reversal of this conversion process is more interesting. The previously used system's output format and custom specifiers also apply in the process of string to date. The most important point in the string to date process 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 (Dateformatter.date (from: datestring)//2016-12-02 10:15:59 +0000
      • It is important to note that the time of the string is 18:15:59, and the output time is 10:15:59, because I am in the time zone of Beijing, that is, East eight, and the default output is in Greenwich Mean time output, that is, 8 hours apart.

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

        datestring = "Mon, Geneva, 20:00:01 GMT" Dateformatter.dateformat = "E, DD, MM yyyy HH:mm:ss zzz" datefromstring = Date Formatter.date (from:datestring) print (datefromstring)//2008-08-08 20:00:01 +0000
datecomponents
  • In many scenarios, you might want to disassemble the value of a date to extract a specific value from it. For example, you might want to get a value for days and months in a date, or you can get the value of hours and minutes from the time, which will introduce the Datecomponents class to solve this problem. It is important to note that the Datecomponents class is often used in conjunction with the calendar, specifically, the method of the Calendar class is to actually implement the conversion of date to datecomponents, as well as the inverse conversion. Remember this, First get the Currentcalendar object, and assign it to a constant for later use.

    Let calendar = Calendar.current ()
  • The following code shows a typical example of the process of datecomponents by date.

    let datecomponents = calendar.components ([ Calendar.unit.era, calendar.unit.year,    calendar.unit.month, calendar.unit.day , calendar.unit.hour, calendar.unit.minute,   calendar.unit.second], from:  currentdate) Print ("era: (Datecomponents.era)  year: (datecomponents.year)  month: (Datecomponents.month)  day:  (Datecomponents.day)  hour: (Datecomponents.hour)  minute: (Datecomponents.minute)   second:   (Datecomponents.second) ")// era:optional (1)  year:optional  month:O Ptional (8)  day:optional ( hour:optional)      minute:optional ()   Second:optional (+) 
      • The method in the Calendar class is used components(_:from:) . This method receives two parameters, the second passed in is the date object to be disassembled, the first parameter is interesting, the parameter is an array, which is put into the constituent date of each component unit (CALENDAR.UNIT), such as the month (Calendar.Unit.month), Sun (Calendar.Unit.day).

      • Calendar.unit is a struct, and all of its properties and descriptions can be viewed in the official documentation.

      • It is also important to note that in the components(_:from:) first array parameter of the method, if you do not pass in the name of the unit that you want to resolve, then you cannot get the unit from the Datecomponents object, such as the method above does not pass in the Calendar.Unit.month, Then when the last print, if the value is printed, the resulting value will be nil.

        datecomponents = Calendar.components ([Calendar.Unit.year], from:currentdate) print ("Year: (Datecomponents.year) Month: (datecomponents.month) ")//Optional Month:nil
  • Datecomponents-Date

      • The conversion of
      • Datecomponents-date is also very simple, just to initialize a Datecomponents object, Then specify the specific components, and finally call the Calendar class's datefromcomponents: method to complete the conversion

        var  Components = datecomponents () components.year = 1985components.month =  02components.day = 05components.hour = 07components.minute = 08components.second  = 44let datefromcomponents = calendar.date (from: components) print ( datefromcomponents)  // optional (1985-02-04 23:08:44 +0000) 
  • It is also possible to set different time zones to get local time:

    Components.timezone = timeZone (abbreviation: "GMT")//Greenwich Mean timecomponents.timezone = timeZone (abbreviation: " CST ")//Timecomponents.timezone = timeZone (abbreviation:" CET ")//Central European time
compare dates and times
    • In addition to the application scenarios mentioned above, another common scenario for dates and times is comparison. Compare two date objects to determine which date is earlier or later, or whether the date is the same. Here will be introduced 3 ways to do comparisons, methods do not distinguish between good and bad, suitable for their own needs the most important.

    • Before you begin the comparison, create two date objects for the following comparison:

      Dateformatter.dateformat = "MMM dd, yyyy zzz" datestring = "may, GMT" var date1 = dateformatter.date (From:datestrin g) datestring = "May, GMT" var date2 = dateformatter.date (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 Date1 and date2 two dates which are earlier or later, use the and methods provided by the NSDate earlierDate: class laterDate: to implement.

      Print ((date1! as NSDate). Earlierdate (date2!))//2016-05-08 00:00:00 +0000print ((date1! as NSDate). Laterdate (date2!))/ /2016-05-10 00:00:00 +0000
      • When the earlierDate: method is used, the return value is the NSDate object with an earlier date; laterDate: The return value of the NSDate object is a later date.

      • The above method, because Date1 and date2 belong to the date class, earlierDate: and the laterDate: parameter type that the method wants to receive is nsdate, the type conversion is done first.

Method 2 (compare:)
    • The second method of comparison is to use the method provided by the date struct compare: , and the return value is an enumeration of type Comparisonresult.

      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 little different, the principle is to compare date1 and date2 with a reference date, and then judge the gap of two dates by judging the gap between two dates and reference dates.

    • For example: Compare 4 and 102 numbers, 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 dates
    • Another interesting scenario for working with dates is the calculation of dates. For example, calculate the 2016-08-12 number plus 2 months 12 days is how much such calculations. Here are two different ways to do date calculations. The first 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 false assumption calculates the current date plus 2 months and 5 days

      Let Monthstoadd = 2let Daystoadd = 5
Method 1
var calculateddate = calendar.date (ByAdding:Calendar.Unit.month, Value:monthstoadd, To:currentdate, Options:calendar .   Options.init (rawvalue:0)) Calculateddate = Calendar.date (ByAdding:Calendar.Unit.day, 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 is to add a specific date unit value to the existing date value, and then return a new Date object. Because the example here is to add two values, you need to call the method two times.

Method 2
    • Method 1, although feasible, but there is a disadvantage, that is, every unit of computation needs to call the method separately, if you want to give the current date plus 7 years 3 months 4 days 8 hours 23 minutes 34 seconds, then call the dateByAddingUnit:value:toDate:options: Method 6 times! And Method 2 can solve this problem. And Method 2 was once used in the Datecomponents class.

    • I will first initialize a new Datecomponents object, then set the month and the number of days, and then call the method named in the Calendar class dateByAddingComponents:toDate:options: , the return value of which is the calculated Date object.

      var newdatecomponents = datecomponents () newdatecomponents.month = 2newdatecomponents.day = 5calculatedDate = Calendar.date (byadding:newdatecomponents, To:currentdate, Options:Calendar.Options.init (rawvalue:0)) print ( calculateddate)//Optional (2016-10-24-08:47:57 +0000)
calculation of the date difference value
    • Calculating the exact difference between two days is also a common problem when working with date objects. The 3 method is described here to resolve the problem.

    • First, customize the two date objects first:

      Dateformatter.dateformat = "Yyyy-mm-dd HH:mm:ss" datestring = "2016-08-08 18:25:17" date1 = Dateformatter.date (from: datestring) datestring = "1985-02-05 07:45:38" date2 = Dateformatter.date (from:datestring)
Method 1
    • Method 1 uses an object method in the Calendar class components:from:to:options: .

      var diffcomponents = calendar.components ([Calendar.Unit.year, Calendar.Unit.month, Calendar.Unit.day], from:date2!, to:date1!, Options:Calendar.Options.init (rawvalue:0)) print ("Date1 and Date2 is different in (diffcomponents.year)  Years (Diffcomponents.month) months and (diffcomponents.year) days ")//Date1 and Date2 is different in Optional (+) years Optional (6) months and Optional days
      • components:from:to:options:The first parameter in the method also receives an array containing the calendar.unit struct. Because it is from date2 than Date1, the return value in ascending order is a positive number, and if it is reversed, the return value is a negative number.

Method 2
    • The second method described here will be used for the first time to the Datecomponentsformatter class. The Datecomponentsformatter class provides a number of different methods for automatic calculation during the day, and the return value is a formatted string.

    • The
    • Initializes a Datecomponentsformatter object first, and then it first specifies one of its property 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 specifies the format of the output of the final result. Using full here, the units that represent the output of the result are displayed, such as Monday,june. If you want to use shorthand, You can reset the properties. All attribute values are listed in the official documentation.

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 Before you use this method, you must set a calendar unit at least in the Allowedunits property, otherwise this method will return nil, so before using this method, specify how you want to see the output, Then let's execute the output method.

Summary

As I said in the abstract, processing dates are common and unavoidable in everyday code, where I introduce some common ways of dealing with dates with small snippets. Either the NSDate class, the date struct, or the class associated with it, has only one purpose, which is the ability to process the date quickly. If you want to take a closer look at the date, or to practice in the daily coding process, read the official documentation.

Guidelines on the use of date classes in Swift3.0

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: info-contact@alibabacloud.com 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.