How to get accuracy completion days count from given input date
func floatDifferenceDays() -> Double {
let current = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let inputDate : String = "2018-07-15 05:46:12"
let input = dateFormatter.date(from: inputDate)
var result = current.timeIntervalSince(input!)
result = result / 86400
return result
}
Its zero. since the cycle of days datecomonents.day till 31 and increments to Month followed by year.
How can get the days that cycle have taken place which not include year,months.
if given inputdate 12 hours back from current date its should return 0.5 days completed
I would suggest you use Calendar and DateComponents to get the correct elapsed time between two dates. This will cater for leap years and daylight savings time changes.
E.g.
let current = Date()
let dateFormatter = DateFormatter()
let calendar = Calendar.autoupdatingCurrent
let timezone = TimeZone.autoupdatingCurrent
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let inputDate = "2018-07-15 05:46:12"
if let input = dateFormatter.date(from: inputDate) {
let components = calendar.dateComponents([.day,.hour], from: input, to: current)
let days = Float(components.day ?? 0)
let hours = Float(components.hour ?? 0)
let elapsed = days + hours/24.0
print("elapsed time is \(elapsed) days")
}
elapsed time is 366.25 days
Note that this code assumes that the input string is in the "local" timezone; If it isn't you would need to make appropriate changes.
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 have to compare the time duration of the recorded audio file against a fixed time duration value of 10 mins (10:00). The duration of the audio file is a string.
Doing string comparison works fine if the format of recorded files duration and the format of the fixed duration is same i.e mm:ss. If the audio file has duration of format hh:mm:ss , it gives false values in certain cases.
Is there any way to handle this?
You can use this String Extension to calculate total minutes from string
extension String {
func getTimeInSeconds()-> Int? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm:ss" //Your date format
dateFormatter.timeZone = TimeZone.current //Current time zone
var date = Date()
if let getDate = dateFormatter.date(from: self) {//according to date format your date string
date = getDate //Convert String to Date
} else {
dateFormatter.dateFormat = "hh:mm:ss"
if let getDate = dateFormatter.date(from: self) {//according to date format your date string
date = getDate //Convert String to Date
} else {
return nil
}
}
let calendar = Calendar.current
let components = calendar.dateComponents([.hour, .minute,.second], from: date)
let hour = components.hour ?? 0
let minute = components.minute ?? 0
let seconds = components.second ?? 0
return (hour * 360) + minute*60 + seconds
}
}
You can use this extension like this
let getSeconds = "01:20".getTimeInSeconds()
it will cover both formats mm:ss and hh:mm:ss and return seconds ... you can use these seconds to compare instead of string
I am not sure what I am doing wrong, I need to find difference between two dates and extract seconds from it, below is my code. I am not getting correct seconds. There is difference of seconds.
public func captureStartTime() {
captureStartDateTime = Date()
}
public func captureEndTime(eventType: String, eventElement: String) {
let difference = Date().timeIntervalSince(captureStartDateTime)
let interval = Int(difference)
let seconds = interval % 60
let secondsDescrp = String(format: "%02d", seconds)
}
interval is the answer you want. That is the total number of seconds between the two dates.
Your seconds value would only be useful if you wanted to calculate the number of hours, minutes, and seconds or the number of minutes and seconds from the total number of seconds.
Use the following code to get the difference between two dates, Store current time in startTime when pressed button 1 and store current date time in endTime when pressed button 2, See this code, I hope this helps you.
var startTime:Date!
var endTime:Date!
#IBAction func buttonStartTime(_ sender: UIButton) {
startTime = Date()
}
#IBAction func buttonEndTime(_ sender: UIButton) {
endTime = Date()
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.second]
formatter.unitsStyle = .full
let difference = formatter.string(from: startTime, to: endTime)!
print(difference)//output "8 seconds"
}
Output
8 seconds
you can also use default date components and according to that compare your dates and you can get the difference in year, month, day etc
let dateString1 = "2019-03-07T14:20:20.000Z"
let dateString2 = "2019-03-07T14:20:40.000Z"
//set date formate
let Dateformatter = DateFormatter()
Dateformatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
//convert string to date
let dateold = Dateformatter.date(from: dateString1)!
let datenew = Dateformatter.date(from: dateString2)!
//use default datecomponents with two dates
let calendar1 = Calendar.current
let components = calendar1.dateComponents([.year,.month,.day,.hour,.minute,.second], from: dateold, to: datenew)
let seconds = components.second
print("Seconds: \(seconds)")
I have a datePickerthat I use to select a starting date and time, and a durationTextLabelto add minutes to that date and time. I set the duration to be minimum 30 if no text is inserted, but the value in
resulting date and time is identical.
Can you see where I'm mistaking?
Thank you very much as usual.
Here's the function:
func setQueryParameters() {
let dateFormatter = DateFormatter()
var convertedDate: String!
dateFormatter.dateFormat = "yyyy/MM/dd/hh/mm"
convertedDate = dateFormatter.string(from: datePicker.date)
let calendar = Calendar.current
let components = (calendar as NSCalendar).components([.year, .month, .day, .weekday, .hour, .minute] , from: datePicker.date)
let year: Int = components.year!
let month: Int = components.month!
let day: Int = components.day!
let weekday: Int = components.weekday!
let hour: Int = components.hour!
let minute: Int = components.minute!
var duration: Double?
duration = Double(durationTextField.text!)
let endDate = datePicker.date.addingTimeInterval(duration!)
let endComponents = (calendar as NSCalendar).components([.hour, .minute], from: endDate)
let endHour: Int = endComponents.hour!
let endMinute: Int = endComponents.minute!
if durationTextField.text != nil {
duration = Double(durationTextField.text!) ?? 30.00
} else { return}
// Opening Time Query parameter
openingTimeQueryStart = Int("\(String(describing: weekday))"+"00"+"00")!
openingTimeQueryEnd = Int("\(String(describing: weekday))"+"\(String(describing: hour))"+"\(String(describing: minute))")!
print("opening query is \(openingTimeQueryEnd)")
// Closing Time Query parameter
closingTimeQueryStart = Int("\(String(describing: weekday))"+"\(String(endHour))"+"\(String(endMinute))")!
closingTimeQueryEnd = Int("\(String(describing: weekday))"+"00"+"00")!
print("closing time query is \(closingTimeQueryStart)")
// Booking Query parameter
let bookingQueryString = "\(String(describing: year))"+"\(String(describing: month))"+"\(String(describing: day))"+"\(String(describing: weekday))"+"\(String(describing: hour))"+"\(String(describing: minute))"+"\(String(endHour))"+"\(String(endMinute))"
bookingQuery = Int(bookingQueryString)!// ?? openingTimeQuery // found nil unwripping optional
}
There are many problems here.
You actually never make any use of dateFormatter other than creating and then never using convertedDate. So delete that unused code.
You have indicated at duration should be in minutes but you treat it as seconds. You need to multiply by 60 to convert it to minutes.
All of your code for calculating things such as openingTimeQueryEnd depend on each value being two digits but your code doesn't give the desired results.
For example, the line:
openingTimeQueryEnd = Int("\(String(describing: weekday))"+"\(String(describing: hour))"+"\(String(describing: minute))")!
should be rewritten as:
openingTimeQueryEnd = Int(String(format: "%02d%02d%02d", weekday, hour, minute))!
or as:
openingTimeQueryEnd = weekday * 10000 + hour * 100 + minute
Make similar changes to the other similar lines.
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.