Reputation: 533
I want to convert seconds to minutes and seconds in HH:SS format but my logic don't give me what I want.
static double toMin (var value){
return (value/60);
}
I also want to be able to add the remainder to the minutes value because sometimes my division gives me a seconds value more that 60 which is not accurate
Upvotes: 4
Views: 5250
Reputation: 7222
you can do something like this:
void main() {
print(toMMSS(100));
}
String toMMSS(int value) =>
'${formatDecimal(value ~/ 60)}:${formatDecimal(value % 60)}';
String formatDecimal(num value) => '$value'.padLeft(2, '0');
or
String toMMSS(int value) =>
'${(value ~/ 60).toString().padLeft(2, '0')}:${(value % 60).toString().padLeft(2, '0')}';
also, you can create an extension
on int
:
extension DateTimeExtension on int {
String get toMMSS =>
'${(this ~/ 60).toString().padLeft(2, '0')}:${(this % 60).toString().padLeft(2, '0')}';
}
usage:
print(342.toMMSS);
Upvotes: 4
Reputation: 994
You could try the solution below, this is how I'm doing it:
String formatHHMMSS(int seconds) {
if (seconds != null && seconds != 0) {
int hours = (seconds / 3600).truncate();
seconds = (seconds % 3600).truncate();
int minutes = (seconds / 60).truncate();
String hoursStr = (hours).toString().padLeft(2, '0');
String minutesStr = (minutes).toString().padLeft(2, '0');
String secondsStr = (seconds % 60).toString().padLeft(2, '0');
if (hours == 0) {
return "$minutesStr:$secondsStr";
}
return "$hoursStr:$minutesStr:$secondsStr";
} else {
return "";
}
}
Upvotes: 2
Reputation: 90045
The Duration
class can do most of the work for you.
var minutes = Duration(seconds: seconds).inMinutes;
You could generate a String
in a mm:ss
format by doing:
String formatDuration(int totalSeconds) {
final duration = Duration(seconds: totalSeconds);
final minutes = duration.inMinutes;
final seconds = totalSeconds % 60;
final minutesString = '$minutes'.padLeft(2, '0');
final secondsString = '$seconds'.padLeft(2, '0');
return '$minutesString:$secondsString';
}
That said, I recommend against using a mm:ss
format since, without context, it's unclear whether "12:34" represents 12 minutes, 34 seconds or 12 hours, 34 minutes. I suggest instead using 12m34s, which is unambiguous.
Upvotes: 9
Reputation: 11
static String formatYMDHMSBySeconds(int milliseconds) {
if (milliseconds == null) {
return '';
}
DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(milliseconds);
return DateFormat("yyyy-MM-dd HH:mm:ss").format(dateTime);
}
Upvotes: -1