Max Max - 2 years ago 122
Swift Question

Date Conversion and date difference issue in swift

In one of my app I have date and time for multiple data fetching from server. I have shown this in tableview. Now from this I have to find some idle time for particular row by some condition by previous and next row's date and time difference. Something like departure and arrival of vehicle and idle time in between. I will show you the issued code where the issue occurs (only for I have both valid date).

let dFormater = NSDateFormatter()
dFormater.dateFormat = "ddMMMYYHHmm"
dFormater.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dFormater.timeZone = NSTimeZone(name: "GMT")
dFormater.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)


if let validFdate : NSDate = dFormater.dateFromString(startDate) {

if let validLdate : NSDate = dFormater.dateFromString(endDate) {


let minutes = validLdate.minutesFrom(validFdate)

print("LO P & N \(indexPath.row)= \(minutes)")

let hour = minutes/60
let min = minutes%60

let fullTime = NSString.init(format: "%02d:%02d", Int(hour),Int(min))
strToReturn = fullTime as String


And log for this is like

2015-12-20 08:41:00 +0000
2015-12-20 00:12:00 +0000
LO P & N 0= -509.0
2015-12-20 04:01:00 +0000
2015-12-19 23:36:00 +0000
LO P & N 0= -265.0
2015-12-20 00:00:00 +0000
2015-12-20 15:57:00 +0000
LO P & N 2= 957.0
2015-12-19 19:19:00 +0000
2015-12-20 10:46:00 +0000
LO P & N 1= 927.0

Now From this logged output, you can see that thought there is valid date in first two still it show wrong output as there are different date and in last two output there is perfect output as both date are of same date. And also why it changes date month and year. See


2015-12-20 08:41:00 +0000

(I have asked another question only for date here)

Answer Source

Your date format is incorrect.

dFormater.dateFormat = "ddMMMYYHHmm"

Capital Y is the year in week-of-year based calendars. You need to use lower case Y:

dFormater.dateFormat = "ddMMMyyHHmm"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download