Date Conversion and date difference issue in swift

2019-09-16 07:44发布

问题:

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)

print(startDate)
print(endDate)

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

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

        print(validFdate)
        print(validLdate)

        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

03JUN161411
04JUN160542
2015-12-20 08:41:00 +0000
2015-12-20 00:12:00 +0000
LO P & N 0= -509.0
04JUN160931
05JUN160506
2015-12-20 04:01:00 +0000
2015-12-19 23:36:00 +0000
LO P & N 0= -265.0
07JUN160530
07JUN162127
2015-12-20 00:00:00 +0000
2015-12-20 15:57:00 +0000
LO P & N 2= 957.0
08JUN160049
08JUN161616
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

03JUN161411

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

(I have asked another question only for date here)

回答1:

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"