iOS Format String into Minutes and Seconds

iOS Format String into minutes and seconds

Assuming the duration value is really the duration in seconds, then you can calculate the number of minutes and seconds and then format those into a string.

int duration = ... // some duration from the JSON
int minutes = duration / 60;
int seconds = duration % 60;

NSString *time = [NSString stringWithFormat:@"%d:%02d", minutes, seconds];

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.

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)
}

Format timer label to hours:minutes:seconds in Swift

Your calculations are all wrong.

let hours = Int(time) / 3600
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format:"%02i:%02i:%02i", hours, minutes, seconds)

format countdown from total seconds to minute and seconds

Right now, you are just converting the integer representing the number of seconds directly to a string, in these two places:

@objc func startHit() {
timer.invalidate()
counter = convertToSeconds(from: enterTime.text!)
lblTime.text = String(counter) <--------
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
}

@objc func timerAction() {
counter -= 1
lblTime.text = String(counter) <--------
if ( counter == 0 ) {
timer.invalidate()
}
}

You need to change these two places to use a more complicated formatting logic, to turn something like 720 to 12:00:

@objc func startHit() {
timer.invalidate()
counter = convertToSeconds(from: enterTime.text!)
lblTime.text = formatSeconds(counter)
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
}

@objc func timerAction() {
counter -= 1
lblTime.text = formatSeconds(counter)
if ( counter == 0 ) {
timer.invalidate()
}
}

And here is the implementation of formatSeconds, which makes use of a DateComponentsFormatter. This is a formatter that is great for formatting amounts of time like this.

func formatSeconds(_ totalSeconds: Int) -> String {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [.minute, .second]
formatter.zeroFormattingBehavior = .pad
return formatter.string(from: TimeInterval(totalSeconds))!
}

Swift: Formatting time string based on number of seconds

(NS)DateComponentsFormatter can do that:

func timeStringFor(seconds : Int) -> String
{
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.second, .minute, .hour]
formatter.zeroFormattingBehavior = .pad
let output = formatter.string(from: TimeInterval(seconds))!
return seconds < 3600 ? output.substring(from: output.range(of: ":")!.upperBound) : output
}

print(timeStringFor(seconds:1)) // 00:01
print(timeStringFor(seconds:60)) // 01:00
print(timeStringFor(seconds:6650)) // 1:50:50

MInutes and seconds with 2 digits

The problem with your second approach is that it expects an integer and you are passing a string.

let minutes = totalTime / 60 
let seconds = totalTime % 60

label.text = String(format: "%02d:%02d", minutes, seconds)

Convert Seconds Integer To HH:MM, iPhone

I was looking for the same thing that you are looking but couldn't find one. So I wrote one -

- (NSString *)timeFormatted:(int)totalSeconds
{

int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;

return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
}

works perfectly in Swift as well:

 func timeFormatted(totalSeconds: Int) -> String {
let seconds: Int = totalSeconds % 60
let minutes: Int = (totalSeconds / 60) % 60
let hours: Int = totalSeconds / 3600
return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}

Convert seconds into minutes and seconds

You will obtain minutes with :

int minutes = totalSeconds / 60;

and remaining seconds with:

int seconds = totalSeconds % 60;.


Related Topics



Leave a reply



Submit