Find minutes remaining between two times - swift

I have two times in the format HH:MM how would I compare the second from the first one finding how many minutes left until I reach to the first time:
example:
timeOne = 12:01
timeTwo = 11:32
output = 29 minutes
Any help writing this in Swift?

NSCalendar can diff dates easily (assuming start and end are NSDate instances
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.Minute, fromDate: start, toDate: end, options: [])
components.minute
If you are interested in getting just the formatted string, and not the actual value, then checkout NSDateComponentsFormatter:
let formatter = NSDateComponentsFormatter()
formatter.allowedUnits = .Minute
formatter.unitsStyle = .SpellOut
// includesTimeRemainingPhrase gives strings like "T minutes remaining"
formatter.stringFromDate(start, toDate: end)
By changing the unitsStyle, you could get different representations, such as:
"54m"
"54 minutes"
"54 min"
"fifty-four minutes"

You should operate with 2 NSDate instances, then you may use next API:
let interval = laterDate.timeIntervalSinceDate(earlierDate)
It returns the number of seconds, as an NSTimeInterval value.
Divide it by 60 will give you minutes.

Related

Converting second to date in Swift

Hello I am trying to make a count down. I want to convert an integer from second to date and show in a label with this below formats. Lets say that 2.500.000 it prints out to label 29 days 22 hour
29 days 22 hour remained
15 hour 30 minutes remained
15 minutes remained
It sounds like you want a DateComponentsFormatter . That lets you generate strings that describe amounts of time rather than dates.
You could use the function func string(from ti: TimeInterval) -> String? which takes a time interval and converts it to a string describing an amount of time.
The following code, loosely based on the example code in Apple's documentation on DateComponentsFormatter:
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.includesApproximationPhrase = true
formatter.includesTimeRemainingPhrase = true
formatter.allowedUnits = [.day, .hour, .minute, .second]
print(formatter.string(from: 123456.7) ?? "nil")
Generates the string About 1 day, 10 hours, 17 minutes, 36 seconds remaining (At least with a US English locale.)

Swift get the remaining seconds of time on target string date

The current date time today was May 9, 2020 10:03 PM, and I have a target string date with the value of 2020-05-09 22:07:30 with the format of yyyy-MM-dd HH:mm:ss.
How can I get the remaining date from that 2 date and print the value with the string of 04:30 as the range of those 2 dates are 4 minutes and 30 seconds
What I can only do is convert the milliseconds to time format like
func msToTime(ms: Int) {
let seconds = ms % 60
let minutes = ms / 60000
return String(format: "%0.2d:%0.2d",minutes,seconds)
}
Output 04:30
But I don't know how to get the range of milliseconds from today's date time to target's date time.
Or if there's any other easier way to do it?
You can use Calendar and DateComponents to easily calculate differences between dates in whatever units you desire. For example, this gets the difference in minutes and seconds:
let dateformatter = DateFormatter()
dateformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateformatter.date(from: "2020-05-09 22:07:30")!
let now = Date()
let components = Calendar.current.dateComponents([.minute, .second], from: now, to: date)
print("difference: \(components.minute!):\(components.second!)")
A straightforward way, with no calculation of any kind needed:
let d1 = Date()
let s = "2020-05-09 22:07:30"
let f = DateFormatter()
f.dateFormat = "yyyy-MM-dd HH:mm:ss"
f.timeZone = TimeZone.current // or whatever
if let d2 = f.date(from: s) {
let f = DateComponentsFormatter()
f.unitsStyle = .positional
let result = f.string(from: d1, to: d2)
}
If you don't like the resulting string format of result, you can eliminate pieces of it. — However, note that this works only because no full days are involved. It isn't clear what the range of possible inputs might be or what the desired output would be if the second date were three months into the future, for example.

TimeDifference between minimum date and maximum date

i am completely new in iPhone app development. i am trying to find difference between min_date and max_date in hours. and wants save its value in textfield. Kindly Provide me complete code to find out difference between both of dates. e.g. if min_date: 12/07/1989, 12:00 am and max_date: 13/07/1989,12:00 am , then total hours will be 24 hours. Please provide me code in swift 3.0.
First, use timeIntervalSince to get the difference in seconds:
let timeInterval = max_date.timeIntervalSince(min_date)
Then you can do some maths to calculate the number of hours
let hours = timeInterval / 60 / 60
You can choose to floor or ceiling this number, depending on your requirements.
let previousDate = ...
let now = Date()
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [.month, .day, .hour, .minute, .second]
formatter.maximumUnitCount = 2 // often, you don't care about seconds
if the elapsed time is in months, so you'll set max unit to whatever is
appropriate in your case
let string = formatter.string(from: previousDate, to: now)
let minDate = Date() // your min date
let maxDate = Date() // your max date
let components = Calendar.current.dateComponents([.hour], from: minDate, to: maxDate)
It's the most flexible method for search difference between two dates. You can use other components to search for months, days, years etc.

Test whether current time of day is between two TimeIntervals

I have 2 TimeIntervals, which just represent date-agnostic times of day (e.g. 8:00 AM and 5:00 PM). So 0 represents exactly midnight, in this case, and 29,040 represents 8:04 AM. I want to check if the phone's time of day is between the two TimeIntervals.
I found a few similar Stack Overflow questions, but none of them really dealt with TimeIntervals. It seems like just using start <= Date().timeIntervalSinceReferenceDate <= end or something wouldn't work, because it would return a huge value.
What's the best way to handle this type of situation in Swift 3?
Edit: To clarify, I don't need to worry about things like daylight savings. As an example, assume that the user only wants certain things in the app to happen between the hours of X and Y, where X and Y are given to me as TimeInterval values since midnight. So it should be sufficient to check if the phone's TimeInterval since midnight on a typical day is between X and Y before completing the action.
Date().timeIntervalSinceReferenceDate returns the number of seconds since Jan 1, 2000 so no doubt it's a huge number.
It's inadvisable to store time as seconds since midnight due to this naggy little thing called Daylight Saving Time. Every year, different countries do it on different days and on different hours. For example, even though Britain and France change their clock on the same day (March 26, 2017), one makes the shift from 1AM to 2AM, the other goes from 2AM to 3AM. That's very easy to make for a mess!
Use DateComponents instead:
let calendar = Calendar.current
let startTimeComponent = DateComponents(calendar: calendar, hour: 8)
let endTimeComponent = DateComponents(calendar: calendar, hour: 17, minute: 30)
let now = Date()
let startOfToday = calendar.startOfDay(for: now)
let startTime = calendar.date(byAdding: startTimeComponent, to: startOfToday)!
let endTime = calendar.date(byAdding: endTimeComponent, to: startOfToday)!
if startTime <= now && now <= endTime {
print("between 8 AM and 5:30 PM")
} else {
print("not between 8 AM and 5:30 PM")
}
I ended up using DateComponents to calculate a TimeInterval.
let components = Calendar.current.dateComponents(
[.hour, .minute, .second], from: Date())
guard let seconds = components.second,
let minutes = components.minute,
let hours = components.hour else
{
return false
}
let currentTime = Double(seconds + minutes * 60 + hours * 60 * 60)
return startTime <= currentTime && currentTime <= endTime

Difference between two dateTimes in seconds vary due to different time zones - Swift 3

I need to find difference between current time (in seconds) and future start time (fetched from my web service in seconds).
I have coded the following :
let currentTime = Int64(Date().timeIntervalSince1970)
var time = Int64(timeArr[indexPath.row])
print("\(currentTime) vs \(time)")
time = time - currentTime
print("difference in time : \(time)")
let seconds = time % 60
let minutes = (time / 60) % 60
let hours = (time / 3600)
My console shows me this output:
1480400929 vs 1480552620
difference in time : 151691
The problem is that my current time is Tue Nov 29 2016 11:58:49 and the start time is 2016-11-30 17:37:00 so the difference in hours should come to around 30 hours whereas it takes the times in different time zones due to which it comes to around 42 hours. How do I fix this? I have gone through many questions for the same but nothing works. Any help would be appreciated.
If you want the difference between two date in Hours, Minutes and seconds you can use DateComponent like this.
let component = Calendar.current.dateComponents([.hour, .minute, .second], from: Date(), to: startDate)
let hours = component.hour ?? 0
let minutes = component.minute ?? 0
let seconds = component.second ?? 0
Edit: To get date from miliseconds use Date(timeIntervalSince1970:) like this.
let startDate = Date(timeIntervalSince1970: miliSeconds / 1000)
Also you can convert string to Date using DateFormatter like this.
let stringDate = "2016-11-30 17:37:00"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
if let startDate = dateFormatter.date(from: stringDate) {
print(startDate)
}