MInutes and seconds with 2 digits - swift

I have an input in seconds I store it in a var:
var totalTime = 60
I want to show it with 2 digits for minutes and 2 digits for seconds:
01:00
What I have tried:
let minutes = String(totalTime / 60)
let seconds = String(totalTime % 60)
label.text = minutes + ":" + seconds
This gives me: 1:0
But I want 01:00
I tried and It does not work:
label.text = String(format: "%02d:%02d", minutes, seconds)

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)

Related

calculate hours/minutes between two times in dart

I want to get/calculate hours and minutes between two times in dart.
Example: if start_time is 17:30 and end_time is 09:00 (day after) it should return total: 15 hours 30 minutes
My code:
check_two_times_is_before(String start_time, String end_time){
var format = DateFormat("HH:mm");
var start = format.parse(start_time);
var end = format.parse(end_time);
if(start.isAfter(end)) {
// do something here
}
}
You can use difference method on DateTime class.
check_two_times_is_before(String start_time, String end_time){
var format = DateFormat("HH:mm");
var start = format.parse(start_time);
var end = format.parse(end_time);
if(start.isAfter(end)) {
end = end.add(Duration(days: 1));
Duration diff = end.difference(start);
final hours = diff.inHours;
final minutes = diff.inMinutes % 60;
print('$hours hours $minutes minutes');
}
}
You can try it with Duration class
Duration duration = end.difference(start).abs();
final hours = duration.inHours;
final minutes = duration.inMinutes % 60;
print('$hours hours $minutes minutes');
The question is pretty old but here is another solution which might help someone.
Duration duration = DateTime.fromMillisecondsSinceEpoch(timestmap).difference(DateTime.now()).abs();
final days = duration.inDays;
final hours = duration.inHours - (days * 24);
final minutes = duration.inMinutes - (days * 24 * 60) - (hours * 60);
final seconds = duration.inSeconds - (days * 24 * 60 * 60) - (hours * 60 * 60) - (minutes * 60);
Nothing to explain here really. We're just using basic algebra. We're getting the total number of milliseconds between the two timestamps and working that down to days, hours, minutes and seconds.

Convert Minutes to HH:MM:SS - Swift

I have some text fields in an array. HH:MM:SS. I'm having two issues, one is when one of the fields is left blank, the app crashes and I want it to just read as "0" if blank. Second, I use below to convert HH:MM:SS to Minutes. I do 0:18:30 and the math below to decimal comes out to 18.5
Now how would I convert this back to HH:MM:SS? array[0] is hours, array[1] is minutes, array[2] is seconds.
stepOne = (Float(array[0])! * 60) + Float(array[1])! + (Float(array[2])! / 60)
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"

Convert dates to multiple formats with SwiftDate

Is it possible to convert a date, say it is in minutes to another format using SwiftDate library? For example:
77 minutes = 1 hour, 17 minutes
Why not to use this library? You can import NSDateTimeAgo.bundle and NSDate+Extension.swift. And to convert your timestamp to lets say 1 hour, 17 minutes you can do like this:
let timestamp = //timestamp or time
let date = Date(timeIntervalSince1970: timestamp!)
let timeAgo = date.timeAgo
print(timeAgo)
I am suggesting you this because it is more lightweight. And if you do not need the "ago" then you can remove those from NSDateTimeAgo.string file.
But you can also do it without any library like this eg with seconds:
func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
func secondsToHoursMinutesSeconds (seconds:Int) -> () {
let (h, m, s) = secondsToHoursMinutesSeconds (seconds: seconds)
print ("\(h) Hours, \(m) Minutes, \(s) Seconds")
}
secondsToHoursMinutesSeconds(seconds: 3000)// it would print 0 Hours, 50 Minutes, 0 Seconds
You can also suit it for your needs(this code is from this answer).

Get 12h hours am/pm Time

I want to display the time from a Slider to a Label. So i must convert the value and get the current day time on it like 00:00 am/pm.
So i need there a stepper how print all 5 steps like (5,10,15,20,25....50,55)
So this code on the bottom don´t run good, have anybody a better way to make that ?
I have try it but it becomes an error when i slider back (zb: when it´s 8:00 am and i slider back to 7:55 am it come for first 7:00 am.
Here is the code:
func valueChange(_ sender: CircleSlider) {
let countmin = Int(Double(sender.value) * 14.4)
var hour = countmin / 60
let mins = countmin - (hour*60)
if hour >= 12 {
hour -= 12
Am.text = "Pm"
} else {
Am.text = "Am"
}
hours = hour
let i = String(mins)
switch i {
case "Nil":
minutes = 00
case "0":
minutes = 00
case "5":
minutes = 05
case "10":
minutes = 10
case "15":
minutes = 15
case "25":
minutes = 25
case "30":
minutes = 30
case "35":
minutes = 35
case "40":
minutes = 40
case "45":
minutes = 45
case "50":
minutes = 50
case "55":
minutes = 55
case "60":
minutes = 60
default:
break
}
self.circleTime.text = "\(String(format: "%02d", hours!)):\(String(format: "%02d", minutes!))"
}
Thank´s for Help :)
I think there's an issue in your method for 7:56, 7:57, 7:58, 7:59 (it is not truncating well). This code should work for you:
func valueChange(_ sender: CircleSlider) {
let countmin = Int(Double(sender.value) * 14.4)
var hour = countmin / 60
let mins = countmin - (hour * 60)
if hour >= 12 {
hour -= 12
Am = "Pm"
} else {
Am = "Am"
}
hours = hour
minutes = roundToFives(Double(mins))
// This fixes when you have hh:60. For instance, it fixes 7:60 to 8:00
if minutes == 60 {
hours = hour + 1
minutes = 0
}
self.circleTime.text = "\(String(format: "%02d", hours!)):\(String(format: "%02d", minutes!))"
}
// idea of this method comes from: http://stackoverflow.com/questions/27922406/round-double-to-closest-10-swift
private func roundToFives(x : Double) -> Int {
return 5 * Int(round(x / 5.0))
}

AVAudioPlayer currentTime exceeds duration

I'm making my own audio player using AVAudioPlayer.
NOTE: "p" is my instance of the player
Here's how I'm reading the track progress in one of the labels:
currentTime.text = [NSString stringWithFormat:#"%d:%02d", (int)p.currentTime / 60, (int)p.currentTime % 60];
Here's how I set the total duration of the track in one of the labels:
int seconds = (int)p.duration % 60;
int minutes = (int)p.duration / 60;
duration.text = [NSString stringWithFormat:#"%d:%02d", minutes, seconds];
When I run the app on the device, the track's current time ALWAYS exceeds the duration (by about 5-10 seconds).
Is this a bug in AVAudioPlayer, or am I not doing it correctly?
NOTE: This behavior also occurs on the device (not just on the simulator)
After finding the seconds by using % 60, you should remove those seconds when converting the remaining for the minutes. For e.g., with the total duration of 119 seconds after finding 59 seconds you should remove that from 119 and then do minute conversion for 60 seconds (119-59). That might solve your problem.
Minutes should be float: 152 seconds / 60.0f = 2.5333 not 2.
That being said, if you want to show the remaining minutes without the seconds you already obtain: int minutes = (p.duration-seconds) / 60
Also, for a better method to format time the way you want to, have a look at the second answer in this question (not the accepted solution).
Here is the function:
func setTimeString(duration: Double)->String {
var audioDurationSeconds = duration
var expression = ""
var minutesString = "00"
var minutesFloat = 0.0
if (audioDurationSeconds)/60 >= 1 {
minutesFloat = (audioDurationSeconds) / 60
audioDurationSeconds = TimeInterval(Int(audioDurationSeconds)%60)
if minutesFloat < 10.0 {
minutesString = String.init(format: "0%.f", floor(minutesFloat))
} else {
minutesString = String.init(format: "%.f", floor(minutesFloat))
}
}
if audioDurationSeconds < 10.0 {
expression = String.init(format: "%#:0%i", minutesString, Int(audioDurationSeconds))
} else {
expression = String.init(format: "%#:%i", minutesString, (Int(audioDurationSeconds)))
}
return expression
}
extension UILabel{
func getTimeString(from duration:Double) -> String{
let hours = Int(duration / 3600)
let minutes = Int(duration / 60) % 60
let seconds = Int(duration.truncatingRemainder(dividingBy: 60))
if hours > 0 {
return String(format: "%i:%02i:%02i", arguments: [hours,minutes,seconds])
}else {
return String(format: "%02i:%02i", arguments: [minutes,seconds])
}
}