How to calculate two date intervals in swift How many hours, in fact a few lines of code can be done, Very easy, enter the following code within the playground
var date1 = "2015-06-26 8:15:10" var dateformatter = NSDateFormatter () Dateformatter.dateformat = "Yyyy-mm-dd Hh:mm:ss" var Dateresult = dateformatter.datefromstring (date1) nsdate () var Gregorian = Nscalendar (calendaridentifier: Nscalendaridentifiergregorian) var result = gregorian!. Components (Nscalendarunit.calendarunithour, fromdate:dateresult!, Todate:nsdate (), options:nscalendaroptions (0)) Result.hour
Attached Playgroud Pictures
What do you do if you want to see how many days are two dates apart?
The first parameter of the components above is hour so there should be a day, go to the definition to see the following static read-only property, change this parameter to get the interval of how many hours.
static Var calendarunitera:nscalendarunit {get} static var calendarunityear:nscalendarunit {get} static var Calendarunitmonth:nscalendarunit {get} static var calendarunitday:nscalendarunit {get} static var calendarun Ithour:nscalendarunit {get} static var calendarunitminute:nscalendarunit {get} static var Calendarunitsecond : nscalendarunit {get} static var calendarunitweekday:nscalendarunit {get} static var Calendarunitweekdayordi Nal:nscalendarunit {Get}
How many hours of two date intervals are calculated in Swift