0

I would like to know how to calculate the difference between the login time and log out time, for Example: Login time: 8:00 AM and Logout time: 5:00 PM, and I should get 9 hours as total hours rendered.

This is the format of the time that is saved to Firebase

     // Set the time
    let timeFormatter = DateFormatter()
    timeFormatter.dateStyle = .none
    timeFormatter.timeStyle = .short
    timeFormatter.amSymbol = "AM"
    timeFormatter.pmSymbol = "PM"

    let timeString = timeFormatter.string(from: date)
TSM
  • 1,225
  • 1
  • 9
  • 17
  • 2
    Possible duplicate of [Difference between 2 dates in weeks and days using swift 3 and xcode 8](https://stackoverflow.com/questions/42294864/difference-between-2-dates-in-weeks-and-days-using-swift-3-and-xcode-8) – aksh1t Sep 27 '17 at 01:55
  • 1
    duplicate of https://stackoverflow.com/a/42017851/2303865 – Leo Dabus Sep 27 '17 at 01:55
  • 1
    @LeoDabus, sorry for that. Thanks for the reminders. Have a great day! – TSM Sep 27 '17 at 01:58
  • 2
    @LeoDabus, I tried the solution you posted on that post and it is what I needed. I should have looked further and could have found your post before asking this question. Thank you so much! Again, I apologize for asking this question. – TSM Sep 27 '17 at 03:16
  • @TSM you are welcome. – Leo Dabus Sep 27 '17 at 03:17
  • Possible duplicate of [Find difference in seconds between NSDates as integer using Swift](https://stackoverflow.com/questions/26599172/find-difference-in-seconds-between-nsdates-as-integer-using-swift) – Jaydeep Vora Sep 27 '17 at 05:17

2 Answers2

6

Edit: Found duplicate question

Create Date objects (link to question) from the login (loginTime) and logout (logoutTime) times, and then use them like so:

let components = Calendar.current.dateComponents([.hour, .minute], from: loginTime, to: logoutTime)

// To get the hours
print(components.hour)
// To get the minutes
print(components.minute)
aksh1t
  • 5,410
  • 1
  • 37
  • 55
3

At login...

    let loginTime = Date()
    UserDefaults.standard.set(loginTime, forKey: "loginTime")

Then at logout...

    let loginTime = UserDefaults.standard.object(forKey: "loginTime") as? Date ?? Date()
    let loginInterval = -loginTime.timeIntervalSinceNow

    let formatter = DateComponentsFormatter()
    formatter.unitsStyle = .full
    formatter.includesApproximationPhrase = false
    formatter.includesTimeRemainingPhrase = false
    formatter.allowedUnits = [.hour, .minute]

    // Use the configured formatter to generate the string.
    let userLoginTimeString = formatter.string(from: loginInterval) ?? ""
    print("user was logged in for \(userLoginTimeString)")
halfer
  • 19,824
  • 17
  • 99
  • 186
ekscrypto
  • 3,718
  • 1
  • 24
  • 38