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)
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)
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)")
Related
I’m trying to convert my AM PM time pickers to 24h format to print the start and end time to calculate the price but i got an unknown error. attached is photo of my UI to simplify the idea and my code.
Note: the end time is automatically shows after i choose the start time
#objc func donePressed(){
// formatter
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
startTimeTxt.text = formatter.string(from: StartTimePicker.date)
self.view.endEditing(true)
endTimeTxt.text = formatter.string(from: EndTimePicker.date)
self.view.endEditing(true)
let starttimecal = StartTimeTxt.text!
let endtimecal = EndTimeTxt.text!
let StartTo24 = starttimecal
let EndTo24 = endtimecal
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
let sTime = dateFormatter.date(from: startTo24)
dateFormatter.dateFormat = "HH:mm"
let sTime24 = dateFormatter.string(from: sTime!)
print("24 hour formatted Date:", sTime24)
let eTime = dateFormatter.date(from: endTo24)
dateFormatter.dateFormat = "HH:mm"
let eTime24 = dateFormatter.string(from: eTime!) // here the fatal error comes after i choose the start time from simulator
print("24 hour formatted Date:", eTime24)
}
To get the 12h time format to display in the text fields you can use the formatter you already have but I also like to set the locale
let dateFormatter12h = DateFormatter()
dateFormatter12h.locale = Locale(identifier: "en_US_POSIX")
dateFormatter12h.dateFormat = "h:mm a"
To calculate the time difference there is a function for that in the Calendar class, here we calculate the number of hours and minutes between two dates (this is an assumption since I don't know exactly what calculation you want to do)
let hourAndMinutes = Calendar.current.dateComponents([.hour, .minute], from: startDate, to: endDate)
Below is a more complete example
//Sample data
let startDate = Date()
let endDate = startDate.addingTimeInterval(3.25*60*60) //add 3h and 15 minutes
// Format and print in 12h format
let dateFormatter12h = DateFormatter()
dateFormatter12h.locale = Locale(identifier: "en_US_POSIX")
dateFormatter12h.dateFormat = "h:mm a"
let start = dateFormatter12h.string(from: startDate)
let end = dateFormatter12h.string(from: endDate)
print(start, end)
// Calculate time difference in hours and minutes
let hourAndMinutes = Calendar.current.dateComponents([.hour, .minute], from: startDate, to: endDate)
print(hourAndMinutes)
// Calculate price, the formula is just an example
let price = hourAndMinutes.hour! * 15 + hourAndMinutes.minute! * 15 / 60
print(price)
Output
6:46 PM 10:01 PM
hour: 3 minute: 15 isLeapMonth: false
48
I would like to notify the user and reset an aspect of the app once a new month begins. This reset needs to repeats every time the month changes.
Using Swift and have used the DateToolsSwift pod.Date Pod
What's the best way to get this to work
func checkIfNewMonth(newDate: Date, oldDate: Date){
var userCalendar = Calendar.current
userCalendar.timeZone = TimeZone(abbreviation: "UTC")!
let oldComponents = userCalendar.dateComponents([.month, .year], from: oldDate)
let newComponents = userCalendar.dateComponents([.month, .year], from: newDate)
guard let oldCompareDate = userCalendar.date(from: oldComponents) else { return }
guard let newCompareDate = userCalendar.date(from: newComponents) else { return }
if newCompareDate > oldCompareDate {
//New date is a new month
} else if newCompareDate < oldCompareDate {
//New date is an previous month
}
}
Thought I'd post a function that does what the op asked. Just feed in the two dates you want to compare. I think UserDefaults would be a great way of storing the old date as well.
The calendar can tell you the range of the current month. The next month begins at the end of the current month:
let startOfNextMonth = Calendar.current.dateInterval(of: .month, for: Date())?.end
let formatter = DateFormatter()
formatter.dateStyle = .long
print(startOfNextMonth.map(formatter.string(from:)) ?? "not a date")
Simply schedule a UNNotificationRequest for this date.
I have an app the records the start time and date using the Calendar.component for each individual calendar component (i.e. let hour = calendar.component(.hour, from:date)) and sends the data to a Google form after another button is pressed. When the Minutes or seconds begins with a 0, the 0 gets dropped and I get a result like this: 4:2:3 for what should be 04:02:03.
Here is the code:
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from:date)
let minutes = calendar.component(.minute, from:date)
let seconds = calendar.component(.second, from:date)
let day = calendar.component(.day, from: date)
let month = calendar.component(.month, from: date)
let year = calendar.component(.year, from: date)
startTime = "\(hour):\(minutes):\(seconds)"
startDate = "\(month)/\(day)/\(year)"
You don't need Calendar & Date Object Separately. Date Object will do both.
DateFormatter is the correct way of doing this.
// unnecessary code
/* let calendar = Calendar.current
let hour = calendar.component(.hour, from:date)
let minutes = calendar.component(.minute, from:date)
let seconds = calendar.component(.second, from:date)
let day = calendar.component(.day, from: date)
let month = calendar.component(.month, from: date)
let year = calendar.component(.year, from: date)
*/
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm:ss"
var startTime = dateFormatter.string(from: date)
dateFormatter.dateFormat = "M/dd/yyyy"
var startDate = dateFormatter.string(from: date)
I need to get the current hour and minute as per the system time format, e.g for system time 7:05 PM, sysHour should be 7. For 19:05, sysHour should be 19
Currently, I am using the code below but it gives sysHour = 19 instead of 7.
let date = Date()
let calendar = Calendar.current
let sysHour = calendar.component(.hour, from: date)
let sysMinutes = calendar.component(.minute, from: date)
Please help
Thanks
Use a DateFormatter using .short or maybe .medium for the timeStyle.
let formatter = DateFormatter()
formatter.timeStyle = .short
formatter.dateStyle = .none
let time = formatter.string(from: Date())
The result will depend on the user's locale and their time settings.
I get from the server a date with this format:
2016-05-27 17:33:43+0400
Now, I want to detect, how much time passed since that date? For example 1 day 5 hours 10 minutes 20 seconds.
How can I do it? I know how to calculate this from the timestamp, but do not know how to convert this to a timestamp.
Can anyone help me with it?
For example:
Convert this 2016-05-27 17:33:43+0400 to 1464370423 this
Or maybe there are another solution. I just want to calculate how much time passed since that time
You can use NSDateComponents formatter to get the relative time between two dates. Regarding the date string format you need to use xx for the time zone part.
let dateStr = "2016-05-27 17:33:43+0400"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ssxx"
formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
if let date = formatter.dateFromString(dateStr) {
print(date) // "2016-05-27 13:33:00 +0000\n" -4hs
let dateComponentsFormatter = NSDateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.Day,.Hour,.Minute,.Second]
dateComponentsFormatter.unitsStyle = .Full
print(dateComponentsFormatter.stringFromDate(date, toDate: NSDate()) ?? "") // 6 days, 17 hours, 51 minutes, 29 seconds
}
given the input string you can convert it to a date and subsequently to an NSTimeInterval since the current time using the following.
let inputDate = "2016-05-27 17:33:43+0400"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZZZZZ"
if let aDate = dateFormatter.dateFromString(inputDate) {
let timeInterval = aDate.timeIntervalSinceNow
let dateComponentsFormatter = NSDateComponentsFormatter()
if let dateString = dateComponentsFormatter.stringFromTimeInterval(abs(timeInterval)) {
print ("Elapsed time=\(dateString)")
}
}
Output:
Elapsed time=6d 17:51:52
You can get the date as the timestamp in your question using aDate.timeIntervalSince1970
I suggest that this could help you: How to get the current time as datetime
You can get the current time and calculate the difference using the server time and your current time.
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute
Hope it helps.
This will tell you
"how many time"
passed since an event.
let date = Date()
let howManyTimePassed = date.timeIntervalSinceNow
TimeInterval is a typealias for a double, meaning its another way to say double. The value of the timeInterval represents seconds.
Try this class in Swift 5.1:
open class MyDateClass: NSObject {
private var result:MyDateTime!
init(dateStr: String, inputFormat: String) {
let formatter = DateFormatter()
formatter.dateFormat = inputFormat //"yyyy-MM-dd HH:mm:ss"
formatter.calendar = Calendar(identifier: .gregorian)
formatter.locale = Locale(identifier: "en_US_POSIX")
if let date = formatter.date(from: dateStr) {
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.year,.month,.day,.hour,.minute,.second]
dateComponentsFormatter.unitsStyle = .full
let strFromat = dateComponentsFormatter.string(from: date, to: Date()) ?? ""
var trimmedString = strFromat.replacingOccurrences(of: " ", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "years", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "months", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "days", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "hours", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "minutes", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "seconds", with: "")
let arr = trimmedString.split(separator: ",")
let result = MyDateTime(year: Int(arr[0]), month: Int(arr[1]), day: Int(arr[2]), hour: Int(arr[3]), minute: Int(arr[4]), second: Int(arr[5]))
self.result = result
}
}
func getDateTime() -> MyDateTime {
return result
}
}
public struct MyDateTime {
var year:Int?
var month:Int?
var day:Int?
var hour:Int?
var minute:Int?
var second:Int?
}
And this class works like this:
let myClass = MyDateClass(dateStr: "2016-05-27 17:33:43", inputFormat: "yyyy-MM-dd HH:mm:ss")
let time = myClass.getDateTime()
Now you can show time as you wish.