Swift - Integer conversion to Hours/Minutes/Seconds
Define
func secondsToHoursMinutesSeconds(_ seconds: Int) -> (Int, Int, Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
Use
> secondsToHoursMinutesSeconds(27005)
(7,30,5)
or
let (h,m,s) = secondsToHoursMinutesSeconds(27005)
The above function makes use of Swift tuples to return three values at once. You destructure the tuple using the let (var, ...)
syntax or can access individual tuple members, if need be.
If you actually need to print it out with the words Hours
etc then use something like this:
func printSecondsToHoursMinutesSeconds(_ seconds: Int) {
let (h, m, s) = secondsToHoursMinutesSeconds(seconds)
print ("\(h) Hours, \(m) Minutes, \(s) Seconds")
}
Note that the above implementation of secondsToHoursMinutesSeconds()
works for Int
arguments. If you want a Double
version you'll need to decide what the return values are - could be (Int, Int, Double)
or could be (Double, Double, Double)
. You could try something like:
func secondsToHoursMinutesSeconds(seconds: Double) -> (Double, Double, Double) {
let (hr, minf) = modf(seconds / 3600)
let (min, secf) = modf(60 * minf)
return (hr, min, 60 * secf)
}
conversion from NSTimeInterval to hour,minutes,seconds,milliseconds in swift
Swift supports remainder calculations on floating-point numbers, so we can use % 1
.
var ms = Int((interval % 1) * 1000)
as in:
func stringFromTimeInterval(interval: TimeInterval) -> NSString {
let ti = NSInteger(interval)
let ms = Int((interval % 1) * 1000)
let seconds = ti % 60
let minutes = (ti / 60) % 60
let hours = (ti / 3600)
return NSString(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms)
}
result:
stringFromTimeInterval(12345.67) "03:25:45.670"
Swift 4:
extension TimeInterval{
func stringFromTimeInterval() -> String {
let time = NSInteger(self)
let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
let seconds = time % 60
let minutes = (time / 60) % 60
let hours = (time / 3600)
return String(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms)
}
}
Use:
self.timeLabel.text = player.duration.stringFromTimeInterval()
Convert seconds into minutes and seconds
You will obtain minutes with :
int minutes = totalSeconds / 60;
and remaining seconds with:
int seconds = totalSeconds % 60;.
How to change the string in seconds to minutes in Swift3?
Here is one method:
let duration: TimeInterval = 540
// new Date object of "now"
let date = Date()
// create Calendar object
let cal = Calendar(identifier: .gregorian)
// get 12 O'Clock am
let start = cal.startOfDay(for: date)
// add your duration
let newDate = start.addingTimeInterval(duration)
// create a DateFormatter
let formatter = DateFormatter()
// set the format to minutes:seconds (leading zero-padded)
formatter.dateFormat = "mm:ss"
let resultString = formatter.string(from: newDate)
// resultString is now "09:00"
// if you want hours
// set the format to hours:minutes:seconds (leading zero-padded)
formatter.dateFormat = "HH:mm:ss"
let resultString = formatter.string(from: newDate)
// resultString is now "00:09:00"
If you want your duration in seconds to be formatted as a "time of day," change the format string to:
formatter.dateFormat = "hh:mm:ss a"
Now, the resulting string should be:
"12:09:00 AM"
This will vary, of course, based on locale.
Convert decimal time to hours and minutes in Swift
I might advise not bothering to calculate hours and minutes at all, but rather let DateComponentsFormatter
do this, creating the final string for you.
For example:
let formatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [.hour, .minute]
return formatter
}()
Then supply this formatter the elapsed time measured in seconds (a TimeInterval
, which is just an alias for Double
):
let remaining: TimeInterval = 90 * 60 // e.g. 90 minutes represented in seconds
if let result = formatter.string(from: remaining) {
print(result)
}
On a English speaking device, that will produce:
1 hour, 30 minutes
The virtue of this approach is that not only does it get you out of the business of manually calculating hours and minutes yourself, but also that the result is easily localized. So, if and when you get around to localizing your app, this string will be localized automatically for you, too, with no further work on your part. For example, if you add German to your app localizations, then the US user will still see the above, but on a German device, it will produce:
1 Stunde und 30 Minuten
If you want it to say how much time is remaining, set includesTimeRemainingPhrase
:
let formatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.includesTimeRemainingPhrase = true
formatter.allowedUnits = [.hour, .minute]
return formatter
}()
That will produce:
1 hour, 30 minutes remaining
If you want a “hh:mm” sort of representation:
let formatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.zeroFormattingBehavior = .pad
formatter.allowedUnits = [.hour, .minute]
return formatter
}()
Will produce:
01:30
Bottom line, if you really want to calculate minutes and seconds, feel free, but if it’s solely to create a string representation, let the DateComponentFormatter
do this for you.
Convert Minutes to HH:MM:SS - Swift
What you need is to calculate the number of seconds instead of number of minutes. Using the reduce method just multiply the first element by 3600 and then divide the multiplier by 60 after each iteration. Next you can use DateComponentsFormatter
to display the resulting seconds time interval using .positional
units style to the user:
let array = [0,18,30]
var n = 3600
let seconds = array.reduce(0) {
defer { n /= 60 }
return $0 + $1 * n
}
let dcf = DateComponentsFormatter()
dcf.allowedUnits = [.hour, .minute, .second]
dcf.unitsStyle = .positional
dcf.zeroFormattingBehavior = .pad
let string = dcf.string(from: TimeInterval(seconds)) // "00:18:30"
How to calculate days, hours, minutes from now to certain date in swift
You need to find out when is the next birth date based on the day and month of birthday. You can use Calendar's method nextDate(after: Date, matching: DateComponents)
func nextDate(after date: Date, matching components: DateComponents, matchingPolicy: Calendar.MatchingPolicy, repeatedTimePolicy: Calendar.RepeatedTimePolicy = default, direction: Calendar.SearchDirection = default) -> Date?
let birthDateCoponents = DateComponents(month: 4, day: 16)
let nextBirthDate = Calendar.current.nextDate(after: Date(), matching: birthDateCoponents, matchingPolicy: .nextTime)!
let difference = Calendar.current.dateComponents([.day, .hour, .minute, .second], from: Date(), to: nextBirthDate)
difference.day // 105
difference.hour // 2
difference.minute // 5
difference.second // 30
When displaying it to the user you can use DateComponentsFormatter with the appropriate unitsStyle
. You can see below how it would look like when using .full
style and limiting the units to .day, .hour, .minute, .second
:
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.day, .hour, .minute, .second]
formatter.unitsStyle = .full
formatter.string(from: Date(), to: nextBirthDate) // "105 days, 1 hour, 44 minutes, 36 seconds"
Related Topics
How to Prevent Tableview Section Head from Sticking While Scrolling
Loading/Downloading Image from Url on Swift
Getting the Difference Between Two Dates (Months/Days/Hours/Minutes/Seconds) in Swift
Applications Are Expected to Have a Root View Controller At the End of Application Launch
How to Add Nsapptransportsecurity to My Info.Plist File
Change User Agent in Uiwebview
How to Resize the Uiimage to Reduce Upload Image Size
How to Have Stored Properties in Swift, the Same Way I Had on Objective-C
Controlling the Screenshot in the iOS 7 Multitasking Switcher
How to Hide Keyboard When Using Swiftui
How to Load Image from Local Path iOS Swift (By Path)
Symbolicating Iphone App Crash Reports
Opening the Settings App from Another App
How to Find Topmost View Controller on Ios
Understanding Ibeacon Distancing
How to Parse a Json File in Swift
How to Preserve Identifierforvendor in iOS After Uninstalling iOS App on Device