11

I'm learning Dart & flutter for 2 days and I'm confused about how to convert seconds (for example 1500sec) to minutes.

For studying the new language, I'm making Pomodoro timer, and for test purposes, I want to convert seconds to MM: SS format. So far, I got this code below, but I'm stuck for a couple of hours now... I googled it but could not solve this problem, so I used Stackoverflow. How should I fix the code?

int timeLeftInSec = 1500;
void startOrStop() {
  timer = Timer.periodic(Duration(seconds: 1), (timer) {
    setState(() {
      if (timeLeftInSec > 0) {
        timeLeftInSec--;
        timeLeft = Duration(minutes: ???, seconds: ???)
      } else {
        timer.cancel();
      }
    }
  }
}

7 Answers7

27

This code works for me

formatedTime({required int timeInSecond}) {
    int sec = time % 60;
    int min = (time / 60).floor();
    String minute = min.toString().length <= 1 ? "0$min" : "$min";
    String second = sec.toString().length <= 1 ? "0$sec" : "$sec";
    return "$minute : $second";
}

now just call the function

formatedTime(timeInSecond: 152)

formated time example

enter image description here

Akash Lilhare
  • 425
  • 7
  • 12
21

Without formatting:

int mins = Duration(seconds: 120).inMinutes; // 2 mins

Formatting:

String formatTime(int seconds) {
  return '${(Duration(seconds: seconds))}'.split('.')[0].padLeft(8, '0');
}

void main() {
  String time = formatTime(3700); // 01:01:11
}
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
  • inMinutes "The returned value can be greater than 59." this answer made me lose 10 minutes chasing the bug thx – cs guy Nov 02 '20 at 15:22
9

You can try this :

int minutes = (seconds / 60).truncate();
String minutesStr = (minutes % 60).toString().padLeft(2, '0');
Augustin R
  • 7,089
  • 3
  • 26
  • 54
griffins
  • 7,079
  • 4
  • 29
  • 54
  • Thank you it's working now. but why I need to put minutes in String minutesStr = (minutes % 60).toString().padLeft(2, '0');? Minutes is now equal to 1 and minutes % 60 is .0166... I think pad left is gonna add two zeros... –  May 28 '20 at 00:09
5

This is the way I've achieved desired format of MM:SS

Duration(seconds: _secondsLeft--).toString().substring(2, 7);

Here is an example of what toString method returns:

d = Duration(days: 0, hours: 1, minutes: 10, microseconds: 500);
d.toString();  // "1:10:00.000500"

So with the substring method chained you can easily achive more formats e.g. HH:MM:SS etc.

Nikage
  • 578
  • 2
  • 7
  • 18
1

There are lot of real answer was given.

I give answer with new and very short method.

for Simplicity I Made function/method.

time format in MM:SS (minute:second)

  String formattedTime(int time) // --> time in form of seconds
  {    
    final int sec = time % 60;
    final int min = (time / 60).floor();
    return "${min.toString().padLeft(2, '0')}:${sec.toString().padLeft(2, '0')}";
  }

time format in HH:MM:SS (hour:minute:second)

  String formattedTime2( int time ) // --> time in form of seconds
  {
    final int hour = (time / 3600).floor();
    final int minute = ((time / 3600 - hour) * 60).floor();
    final int second = ((((time / 3600 - hour) * 60) - minute) * 60).floor();

    final String setTime = [
      if (hour > 0) hour.toString().padLeft(2, "0"),
      minute.toString().padLeft(2, "0"),
      second.toString().padLeft(2, '0'),
    ].join(':');
    return setTime;
  }
0

Check out this piece of code for a count down timer with formatted output

import 'dart:async';

void main(){
  late Timer timer;
  int startSeconds = 120; //time limit
  String timeToShow = "";
  timer =  Timer.periodic(Duration(seconds:1 ),(time){
    startSeconds = startSeconds-1;
    if(startSeconds ==0){
      timer.cancel();
     }

    int minutes = (startSeconds/60).toInt();
    int seconds = (startSeconds%60);
   timeToShow = minutes.toString().padLeft(2,"0")+"."+seconds.toString().padLeft(2,"0");
   print(timeToShow);
  });
}

    /*output
    01.59
    01.58 
    01.57
    ...
    ...
    ...
    00.02
    00.01
    00.00*/
0
static int timePassedFromNow(String? dateTo) {
  if (dateTo != null) {
    DateTime targetDateTime = DateTime.parse(dateTo);
    DateTime dateTimeNow = DateTime.now();
    if (targetDateTime.isAfter(dateTimeNow)) {
      Duration differenceInMinutes = dateTimeNow.difference(targetDateTime);
      return differenceInMinutes.inSeconds;
    }
  }

  return 0;
}

static String timeLeft(int seconds) {
int diff = seconds;

int days = diff ~/ (24 * 60 * 60);
diff -= days * (24 * 60 * 60);
int hours = diff ~/ (60 * 60);
diff -= hours * (60 * 60);
int minutes = diff ~/ (60);
diff -= minutes * (60);

String result = "${twoDigitNumber(days)}:${twoDigitNumber(hours)}:${twoDigitNumber(minutes)}";

return result;
}

static String twoDigitNumber(int? dateTimeNumber) {
  if (dateTimeNumber == null) return "0";
  return (dateTimeNumber < 9 ? "0$dateTimeNumber" : dateTimeNumber).toString();
}
Erfan Eghterafi
  • 4,344
  • 1
  • 33
  • 44