zfdatetool.swift//mystudydemo////Created by Franzhou on 16/6/12.//copyright©2016 year kimree. All rights Reserved.//import Uikitpublic class Zfdatetool:nsobject {//DateFormat default = "Yyyy-mm-dd" Publ IC static var formatstring:string! = "Yyyy-mm-dd" {willset{Self.dateFormatter.dateFormat = newvalue}} private static Le T dateformatter:nsdateformatter = {Let DateFormat = NSDateFormatter () Dateformat.dateformat = ZFDATETOOL.F Ormatstring return DateFormat} ()//MARK:-Get string Time public class Func datefromstring (Datestring:stri Ng, formatstring:string = zfdatetool.formatstring), nsdate? {var DateFormat = Zfdatetool.dateformatter if formatString! = zfdatetool.formatstring{Dateforma t = dateformat.copy () as! NSDateFormatter Dateformat.dateformat = formatString} return dateformat.datefromstring (d atestring)}//MARK:-Get timeString public class Func stringfromdate (Date:nsdate = NSDate (), formatstring:string = zfdatetool.formatstring), Stri ng{var dateformat = Zfdatetool.dateformatter if formatString! = zfdatetool.formatstring{datefor Mat = Dateformatter.copy () as! NSDateFormatter Dateformat.dateformat = formatString} return dateformat.stringfromdate (d ATE)}//MARK:-Timestamp-S public class func timestamp (Date:nsdate = NSDate ()), double{le T timestamp = date.timeintervalsince1970 return timestamp} public class Func Datefromtimestamp (timestamp : Double), nsdate{let date = NSDate (Timeintervalsince1970:timestamp) return date}//MARK: -Get month day week private static let Calendar:nscalendar = {Let calendar = Nscalendar.currentcalendar () Set the first day of the week starting from the beginning of the week, for example://If you want to set starting from Sunday, then firstweekday incoming 1//if required to start from Monday, Firstweekday incoming 2//theSetting only affects Nscalendar does not affect how nsdatecomponents is handled Calendar.firstweekday = 2 return calendar} () public class Func yearwithdate (Date:nsdate = NSDate ()), int{Let components = Calendar.components (nscalend Arunit.year, Fromdate:date) return components.year} public class Func monthwithdate (Date:nsdate = NSDA Te ()), int{Let month = Calendar.ordinalityofunit (Nscalendarunit.month, InUnit:NSCalendarUnit.Year, Fordate: Date) return Month} public class Func daywithdate (Date:nsdate = NSDate ()), int{let day = C Alendar.ordinalityofunit (Nscalendarunit.day, InUnit:NSCalendarUnit.Month, fordate:date) return day} PU Blic class func weekdaywithdate (Date:nsdate = NSDate ()), int{//Calendar.components (Nscalendarunit.weekday, Fromdate:date) The method obtained by weekday is always 1 weeks a day 2 weeks a .... In this order//If you want to get the correct week time after the firstweekday is processed, let weekday = Calendar.ordinalit in the following wayYofunit (Nscalendarunit.weekday, InUnit:NSCalendarUnit.WeekOfYear, fordate:date) return Weekday}}
Basic operations for Swift dates