IOS Date processing (Swift3.0 nsdate)

Source: Internet
Author: User
Tags date1 dateformat time zones local 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.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 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 in fact, the custom output format of the technology is very simple, the specific output format according to the specific requirements, and finally another example ( output format -hours: minutes: Seconds of the week abbreviated 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 19 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, 08, Aug 2008 20:00:01 GMT"
        dateFormatter.dateFormat = "E, dd, MM yyyy HH:mm:ss zzz"
        dateFromString = dateFormatter.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 need to get a value for the number of days and months in a date, or to get the value of hours and minutes from the time, this section introduces 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, you get the Currentcalendar object and assign it to a constant to make it easier to use later.

    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(2016) month:Optional(8) day:Optional(19) hour:Optional(15)     minute:Optional(29) second:Optional(13)


      • The method in the Calendar class is usedcomponents(_: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 thecomponents(_: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(2016) month:nil


  • Datecomponents-Date

      • The conversion of datecomponents. Date is also very simple, just to initialize a Datecomponents object, then specify specific components, and finally call the datefromcomponents of the Calendar class: method to complete the conversion

        var components = DateComponents()
        components.year = 1985
        components.month = 02
        components.day = 05
        components.hour = 07
        components.minute = 08
        components.second = 44
        let 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 Time
    components.timeZone = TimeZone(abbreviation: "CST") // China Standard Time
    components.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 08, 2016 GMT"
      var date1 = dateFormatter.date(from: dateString)
       
      dateString = "May 10, 2016 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 NSDateearlierDate:classlaterDate:to implement.

      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 theearlierDate: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 thelaterDate: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 structcompare:, 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, thedateByAddingUnit: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 thedateByAddingUnit: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 classdateByAddingComponents:toDate:options:, the return value of which is the calculated Date object.

      var newDateComponents = DateComponents()
      newDateComponents.month = 2
      newDateComponents.day = 5
      calculatedDate = 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 classcomponents: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 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


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

    • Initialize a Datecomponentsformatter object first, and then specify one of its property values first.

      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 final result output. Using full here, the unit that represents the output of the result is displayed, such as Monday,june. If you want to use shorthand, you can reset the property. 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 thestringFrom: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.

Summarize


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.






Learn to collect, turn from:



Guidelines on the use of date classes in Swift3.0






Other problems encountered during the development process will be supplemented by the following ...



IOS Date processing (Swift3.0 nsdate)


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.