I've looked at all the Code on here that has to do with getting time duration. All I need to do is simply take a time that is in a label in this format hr:m:s like 20:23:04 for example. I need to take the times from currentTime.StringValue and the time from oldTime.StringValue and then have it show the duration of hours in durationOfTime.StringValue.
So for example say currentTime = 11:00:04 and oldTime = 9:00:04 then I want durationOfTime = 2hr's.
That's it right now I have a code that get's the time and stores it in the format above. However I run into all kinds of problems trying different codes on here that have to do with Time Duration.
Use 2 formatters: a DateFormatter to convert the strings to Date objects and a DateComponentFormatter to display the duration between the 2 Dates:
let currentTimeStr = "11:00:04"
let oldTimeStr = "9:00:04"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "H:mm:ss"
let dateComponentFormatter = DateComponentsFormatter()
dateComponentFormatter.allowedUnits = [.hour, .minute]
dateComponentFormatter.unitsStyle = .short
if let currentTime = dateFormatter.date(from: currentTimeStr),
let oldTime = dateFormatter.date(from: oldTimeStr),
let durationStr = dateComponentFormatter.string(from: oldTime, to: currentTime)
{
print(durationStr) // 2 hrs
}
Hope this is helpful. Edited maddy's suggestion.
let currentTime = "11:00:04"
let oldTime = "9:00:04"
let currentTimeComponents = currentTime.components(separatedBy: ":")
let oldTimeComponents = oldTime.components(separatedBy: ":")
let hrsDifference = Int(currentTimeComponents[0])! - Int(oldTimeComponents[0])!
let minutesDifference = Int(currentTimeComponents[1])! - Int(oldTimeComponents[1])!
let secondsDifference = Int(currentTimeComponents[2])! - Int(oldTimeComponents[2])!
print("hrsDifference = ",hrsDifference)
print("minutesDifference = ",minutesDifference)
print("secondsDifference = ",secondsDifference)
Related
I have an array of objects which the app gets from a WebService, each object has a createdTime and objects are created randomly from 6 in the morning to midnight.
I want to know what is the average time between each object creation.
What is the best and most efficient way to implement it?
The dates are in this format: "CreatedTime": "2019-02-18T22:06:30.523"
The average date interval is the time elapsed between the first and last date and divide by n-1, the number of intervals. That’s going to be most efficient.
This works because the average is equal to the sum of the intervals divided by the number of intervals. But the sum of all the intervals is equal to the difference between the first and last date.
Assuming your date strings are already in order, just grab the first and last, calculate the difference and divide.
let dateStrings = ["2019-02-18T18:06:30.523", "2019-02-18T19:06:30.523", "2019-02-18T21:06:30.523"]
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) // I’m going to assume it’s GMT; what is it really?
guard dateStrings.count > 1,
let lastDateString = dateStrings.last,
let lastDate = dateFormatter.date(from: lastDateString),
let firstDateString = dateStrings.first,
let firstDate = dateFormatter.date(from: firstDateString) else { return }
let average = lastDate.timeIntervalSince(firstDate) / Double(dateStrings.count - 1)
That’s in seconds. If you’d like a nice string format and don’t care about milliseconds, the DateComponentsFormatter is convenient for localized strings:
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.hour, .minute, .second]
dateComponentsFormatter.unitsStyle = .full
let string = dateComponentsFormatter.string(from: average)
That produces:
"1 hour, 30 minutes"
Or you can, less efficiently, build the dates array:
let dateStrings = ["2019-02-18T18:06:30.523", "2019-02-18T19:06:30.523", "2019-02-18T21:06:30.523"]
guard dateStrings.count > 1 else { return }
let dates = dateStrings.map { dateFormatter.date(from: $0)! }
Then you could build an array of intervals between those dates:
var intervals: [TimeInterval] = []
for index in 1 ..< dates.count {
intervals.append(dates[index].timeIntervalSince(dates[index-1]))
}
And then average them:
let average = intervals.reduce(0.0, +) / Double(intervals.count)
And format to taste:
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.hour, .minute, .second]
dateComponentsFormatter.unitsStyle = .full
let string = dateComponentsFormatter.string(from: average)
I am getting Boarding Time from service ( lets say BT- Boarding Time)
I need to find out the differnce between Boarding Time and current time and then find out the difference in Hour , Min.
The condition is user may check the difference between these from any country in the world. so i used UTC to calculate but its giving correct result , kindly help me in this.
func dayStringFromTime() -> String {
let currentTimeUnix = Date().timeIntervalSince1970
let date = NSDate(timeIntervalSince1970: currentTimeUnix)
let dateFormatter = DateFormatter()
// dateFormatter.dateFormat = "HH:mm:ss"
return date.description
}
let CT = dayStringFromTime() //time1
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-mm-dd HH:mm:ss"
let CTDate = formatter.date(from: CT)
let time1 = boardingDateTime//timeformatter.date(from: CT)
let time2 = CT_Date//timeformatter.date(from: ETD)
//You can directly use from here if you have two dates
let interval = time1.timeIntervalSince(time2! as Date)
let hour = (interval ) / 3600;
let minute = interval.truncatingRemainder(dividingBy: 3600) / 60
let intervalInt = Int(interval)
print("\(intervalInt < 0 ? "-" : "+") \(Int(hour)) Hours \(Int(Int(minute))) Minutes")
let minText = Int(minute) > 0 && Int(minute) != 0 ? " \(Int(minute)) min" : (Int(minute) < 0 ? " \(Int(abs(minute))) min" : "")
let hrText = Int(hour) > 0 && Int(hour) != 0 ? " \(Int(hour)) hr" : (Int(hour) < 0 ? " \(Int(abs(hour))) hr" : "")
this url https://stackoverflow.com/a/28608779/3400991 shows the exact problem about this result, kindly help
This is way easier that you have made it out to be:
let boardingTime = Date().addingTimeInterval(3200) // the `addingTimeInterval` is for demonstration purposes only.
let now = Date()
let difference = Calendar.current.dateComponents([.hour, .minute, .second], from: now, to: boardingTime)
print("Boarding will be in: \(difference.hour!):\(difference.minute!):\(difference.second!)")
First of all, be very careful with date/time mathematics, it's not a straight linear conversion, there are lots and lots of rules which go around it and make it ... complicated.
The first thing you need is to calculate the difference between the two times, lucky for you, this is relatively easy...
var boardingTime = Date()
boardingTime = bordingTime.addingTimeInterval(Double.random(in: 0.0..<86400.0))
let now = Date()
let difference = boardingTime.timeIntervalSince(now)
This gives you the number of seconds between these two values (a positive value been the time till, a negative value been the time after)
Next, you need the hours/minutes in some form of human readable notation. It might seem tempting to just start by multiplying and dividing everything by 60, but that would be a mistake and lead you into bad habits (sure over a short range it's not bad, but you need to be very careful)
A better solution would be to use a DateComponentsFormatter...
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
formatter.unitsStyle = .abbreviated
formatter.string(from: difference)
Which will take care of all the "rules" for you, but, it will also localise the results, always a bonus.
The above example will print something like...
10h 28m
What I do is:
How to add minutes to current time in swift
how to add 30 minutes to current time
Here is my code:
endFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let endTimeString = "2017-01-16 12:58:56"
let endTime = endFormatter.dateFromString(endTimeString)
endTime?.dateByAddingTimeInterval(180) // 3 Minute
print(endTime)
1st answer #rob i tried that one but failed . second answer suggest dateByAddingTimeInterval i am not suer is it is work or not .
You need to use dateByAddingUnit as #Rob doing instead of dateByAddingTimeInterval. The reason you are not getting correct time is may because of TimeZone so try to set timeZone with your NSDateFormatter instance.
endFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
endFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
let endTimeString = "2017-01-16 12:58:56"
let endTime = endFormatter.dateFromString(endTimeString)
//Now add the 3 minute in endTime
let calendar = NSCalendar.currentCalendar()
let date = calendar.dateByAddingUnit(.Minute, value: 3, toDate: endTime, options: [])
let dateWithMinuteInterval = Calendar.current.date(byAdding: DateComponents(minute: 23), to: endTime)!
I built a UI that has 3 UIDatePicker
The first UIDatePicker named date will be for Date only (Mode .Date)
Other UIDatePickers names time_from and time_to will be for Time (From time, To time) (Mode .Time)
Then I add a Button,
When I click the button I need to get two variables:
From_DateTime and To_DateTime
(I need the Date from date UI and the time from time_from, time_to
I try a lot but without the desired result:
let date = date.calendar
let date_components = date.components(.Calendar, fromDate: date.date)
let date_from_components = dateFrom.calendar.components(.Calendar, fromDate: dateFrom.date)
let date_to_components = dateTo.calendar.components(.Calendar, fromDate: dateTo.date)
let n = date.calendar.dateBySettingHour(date_from_components.hour, minute: date_from_components.minute, second: 5, ofDate: dateFrom.date, options: NSCalendarOptions.MatchStrictly)
This is an example of fails trying.
I need a simple way to get From_DateTime and To_DateTime
Thanks
Finally I found a way:
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "US")
dateFormatter.dateFormat = "yyyy-MM-dd"
let timeFormatter = NSDateFormatter()
timeFormatter.locale = NSLocale(localeIdentifier: "US")
timeFormatter.dateFormat = " HH:mm"
let date_from = dateFormatter.stringFromDate(date.date) + timeFormatter.stringFromDate(dateFrom.date)
let date_to = dateFormatter.stringFromDate(date.date) + timeFormatter.stringFromDate(dateTo.date)
I am sure there must be another simple way.
I'm trying to do a simple comparison of dates with the intent of moving to another array index based on the day.
Though vastly more efficient than the code I was using, the following (Unable to parse a date) doesn't preserve the timezone offset:
let noaaDate = "2014-08-22T15:00:00-04:00"
let format="yyyy-MM-dd'T'HH:mm:ssZ"
var dateFmt = NSDateFormatter()
dateFmt.dateFormat = format
let newreadableDate = dateFmt.dateFromString(noaaDate)
println(newreadableDate)
Output:
Optional(2014-08-22 19:00:00 +0000)
When I add the following:
dateFmt.timeZone = NSTimeZone.localTimeZone() // I've even tried defaultTimeZone
the output is the same. Where this seems to become an issue is later on when I'm doing the following:
// FYI: parseNOAADateTime is that code above
var earliestTimeNS = parseNOAADateTime(earliestTime!)
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitDay, fromDate: earliestTimeNS)
let dayZero = components.day
// stuff, like starting a loop
let tempDateTimeString = "2014-08-31T01:00:00-04:00"
let thisDateTime = parseNOAADateTime(tempDateTimeString!)
let tempDateTimeComponents = calendar.components(.CalendarUnitDay, fromDate: thisDateTime)
let forecastIndex = tempDateTimeComponents.day - dayZero
Now, forecastIndex SHOULD be 6 because tempDateTimeComponents.day SHOULD be 31. However, they're 5 and 30, respectively, meaning four hour's worth of data is ending up with the previous day's data.
Where am I messing up?
Thanks