Converting Milliseconds to Minutes and Seconds?
Asked Answered
L

21

114

I have looked through previous questions, but none had the answer I was looking for. How do I convert milliseconds from a StopWatch method to Minutes and Seconds? I have:

 watch.start();

to start the stopwatch and

  watch.stop();

to stop the watch. I later have

  watch.getTime();

which returns Milliseconds. I want it to return in Seconds and Minutes. How do I go about doing so? I'm looking for a way to do it without multiplying/dividing by 1000 but rather a method that will make the whole computation more readable and less error-prone.

Letta answered 12/7, 2013 at 21:31 Comment(5)
x milliseconds = x / 1000 seconds. Then z seconds = z / 60 minutes. You could do z % 60 to find the number of seconds remaining.Lodestar
basic math: 1000 milliseconds = 1 seconds. 60 seconds = 1 minute.Jumbled
Check this post:#625933. Should get you what you want.Isatin
This is actually a really simple question. What have you tried?Angola
You can do like this readyandroid.wordpress.com/…Electrokinetic
G
234

I would suggest using TimeUnit. You can use it like this:

long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
Gossip answered 12/7, 2013 at 22:59 Comment(5)
My only issue is I don't know: How to define millis (It is returning as "millis cannot be resolved to a variable" and I don't know how to access it in a System.out.println(); method.Letta
You can do this using just numbers if milliseconds is already something like a long. There is little need to introduce a new library just to do a simple calculation. minutes = ((milliseconds / 1000) / 60)Snavely
This seems to be the best answer for Java 5 through 7.Abound
@Sotti Brilliant? This does not address the Question! The Question asks for minutes and seconds, as the readout of a stopwatch, for example 1 minute 30 seconds This Answer provides minutes or seconds, for example 1 minute 90 seconds.Tonguetied
I would like to use it but with seconds as a double, not ints, for example 1.5s. Is this somethow possible?Maryrosemarys
S
65

After converting millis to seconds (by dividing by 1000), you can use / 60 to get the minutes value, and % 60 (remainder) to get the "seconds in minute" value.

long millis = .....;  // obtained from StopWatch
long minutes = (millis / 1000)  / 60;
int seconds = (int)((millis / 1000) % 60);
Soldier answered 12/7, 2013 at 21:41 Comment(2)
You can do like this readyandroid.wordpress.com/…Electrokinetic
last line was a life saver for the Timer control, using the designer properties instead, thanks!Handcart
T
40

tl;dr

Duration d = Duration.ofMillis( … ) ;
int minutes = d.toMinutesPart() ;
int seconds = d.toSecondsPart() ;

Java 9 and later

In Java 9 and later, create a Duration and call the to…Part methods. In this case: toMinutesPart and toSecondsPart.

Capture the start & stop of your stopwatch.

Instant start = Instant.now(); 
…
Instant stop = Instant.now();

Represent elapsed time in a Duration object.

Duration d = Duration.between( start , stop );

Interrogate for each part, the minutes and the seconds.

int minutes = d.toMinutesPart();
int seconds = d.toSecondsPart();

You might also want to see if your stopwatch ran expectedly long.

Boolean ranTooLong = ( d.toDaysPart() > 0 ) || ( d.toHoursPart() > 0 ) ;

Java 8

In Java 8, the Duration class lacks to…Part methods. You will need to do math as shown in the other Answers.

long entireDurationAsSeconds = d.getSeconds();

Or let Duration do the math.

long minutesPart = d.toMinutes(); 
long secondsPart = d.minusMinutes( minutesPart ).getSeconds() ;

See live code in IdeOne.com.

Interval: 2016-12-18T08:39:34.099Z/2016-12-18T08:41:49.099Z

d.toString(): PT2M15S

d.getSeconds(): 135

Elapsed: 2M 15S

Resolution

FYI, the resolution of now methods changed between Java 8 and Java 9. See this Question.

  • Java 9 captures the moment with a resolution as fine as nanoseconds. Resolution depends on capability of your computer’s hardware. I see microseconds (six digits of decimal fraction) on MacBook Pro Retina with macOS Sierra.
  • Java 8 captures the moment only up to milliseconds. The implementation of Clock is limited to a resolution of milliseconds. So you can store values in nanoseconds but only capture them in milliseconds.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

Tonguetied answered 18/12, 2016 at 0:10 Comment(2)
for android call require api level 26.Poised
@Killer For earlier Android, see the ThreeTen-Backport and ThreeTenABP projects.Tonguetied
M
16

I was creating a mp3 player app for android, so I did it like this to get current time and duration

 private String millisecondsToTime(long milliseconds) {
    long minutes = (milliseconds / 1000) / 60;
    long seconds = (milliseconds / 1000) % 60;
    String secondsStr = Long.toString(seconds);
    String secs;
    if (secondsStr.length() >= 2) {
        secs = secondsStr.substring(0, 2);
    } else {
        secs = "0" + secondsStr;
    }

    return minutes + ":" + secs;
}
Meed answered 9/3, 2018 at 23:51 Comment(0)
R
13

This is just basic math. 1000 milliseconds=1 second and 60000 milliseconds = 1 minute; So just do,

int seconds=(millis/1000)%60;

long minutes=((millis-seconds)/1000)/60;
Ritchey answered 12/7, 2013 at 21:51 Comment(1)
There's a mistake - the second line should be (millis/1000-seconds)/60Barbarity
E
11
  public static String getIntervalTime(long longInterval) {
    
    long intMillis = longInterval;
    long dd = TimeUnit.MILLISECONDS.toDays(intMillis);
    long daysMillis = TimeUnit.DAYS.toMillis(dd);
    intMillis -= daysMillis;
    long hh = TimeUnit.MILLISECONDS.toHours(intMillis);
    long hoursMillis = TimeUnit.HOURS.toMillis(hh);
    intMillis -= hoursMillis;
    long mm = TimeUnit.MILLISECONDS.toMinutes(intMillis);
    long minutesMillis = TimeUnit.MINUTES.toMillis(mm);
    intMillis -= minutesMillis;
    long ss = TimeUnit.MILLISECONDS.toSeconds(intMillis);
    long secondsMillis = TimeUnit.SECONDS.toMillis(ss);
    intMillis -= secondsMillis;

    String stringInterval = "%02d days - %02d:%02d:%02d.%03d";
    return String.format(stringInterval , dd, hh, mm, ss, intMillis);
  }

Shorter Form!

  public static String getIntervalTime(long longInterval) {

    long intMillis = longInterval;
    long dd = TimeUnit.MILLISECONDS.toDays(intMillis);
    intMillis -= TimeUnit.DAYS.toMillis(dd);
    long hh = TimeUnit.MILLISECONDS.toHours(intMillis);
    intMillis -= TimeUnit.HOURS.toMillis(hh);
    long mm = TimeUnit.MILLISECONDS.toMinutes(intMillis);
    intMillis -= TimeUnit.MINUTES.toMillis(mm);
    long ss = TimeUnit.MILLISECONDS.toSeconds(intMillis);
    intMillis -= TimeUnit.SECONDS.toMillis(ss);

    String stringInterval = "%02d days - %02d:%02d:%02d.%03d";
    return String.format(stringInterval , dd, hh, mm, ss, intMillis);
  }

Testing

long delay = 1000*60*20 + 1000*5 + 10;
LOGGER.log(Level.INFO, "Delay Expected {0}", getIntervalTime(delay));

Output

INFO: Delay Expected 00 days - 00:20:05.010
Efficient answered 26/4, 2020 at 23:16 Comment(0)
V
8

To convert time in millis directly to minutes: second format you can use this

String durationText = DateUtils.formatElapsedTime(timeInMillis / 1000));

This will return a string with time in proper formatting. It worked for me.

Valdavaldas answered 21/8, 2018 at 6:17 Comment(2)
Ahah, good one! I just tested on a timer which was in milliseconds and worked!Squishy
Nice approach! Given the formula going around, seems to be Miliseconds / 1000 % 60. Given the timer, will be timer1.Interval in place of Miliseconds etc.Handcart
E
7

I need to convert millisecond to minute and second for timer so I used this code.

private String getTime(long millisecond) {
    
    long min = TimeUnit.MILLISECONDS.toMinutes(millisecond);
    long sec = TimeUnit.MILLISECONDS.toSeconds(millisecond) - 
       TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisecond));

    String time = min + ":" + sec;
    return time;
}

for revers, each minute equals 60,000 millisecond and each second equals 1000 millisecond. So :

 long millisecond = minutes * 60000;
 long millisecond = seconds * 1000;

or

 long millisecond = TimeUnit.SECONDS.toMillis(seconds);
Eraeradiate answered 8/9, 2021 at 6:42 Comment(0)
L
6

X milliseconds = X / 1000 seconds = (X / 1000) / 60 minutes

If you have 100,000 milliseconds, divide this value by 1,000 and you're left with 100 seconds. Now 100 / 60 = 1.666~ minutes, but fractional minutes have no value, so: do 100 % 60 = 40 seconds to find the remainder, then integer division 100 / 60 = 1 minute, with 40 seconds remainder. Answer: 1 minute, 40 seconds.

Lodestar answered 12/7, 2013 at 21:34 Comment(0)
R
6

Here is the full program

import java.util.concurrent.TimeUnit;

public class Milliseconds {

public static void main(String[] args) {
    long milliseconds = 1000000;

    // long minutes = (milliseconds / 1000) / 60;
    long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds);

    // long seconds = (milliseconds / 1000);
    long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds);

    System.out.format("%d Milliseconds = %d minutes\n", milliseconds, minutes );
    System.out.println("Or");
    System.out.format("%d Milliseconds = %d seconds", milliseconds, seconds );

}
}

I found this program here "Link" there it is explained in detail.

Retrorse answered 21/10, 2017 at 14:17 Comment(1)
This does not address the Question. The Question asks for minutes and seconds, as a readout of a stopwatch. You give two separate results, minutes or seconds.dTonguetied
G
5

To get actual hour, minute and seconds as appear on watch try this code

val sec = (milliSec/1000) % 60
val min = ((milliSec/1000) / 60) % 60
val hour = ((milliSec/1000) / 60) / 60
Gesner answered 22/8, 2018 at 11:26 Comment(0)
I
5

You can try proceeding this way:

Pass ms value from

Long ms = watch.getTime();

to

getDisplayValue(ms)

Kotlin implementation:

fun getDisplayValue(ms: Long): String {
        val duration = Duration.ofMillis(ms)
        val minutes = duration.toMinutes()
        val seconds = duration.minusMinutes(minutes).seconds

        return "${minutes}min ${seconds}sec"
}

Java implementation:

public String getDisplayValue(Long ms) {
        Duration duration = Duration.ofMillis(ms);
        Long minutes = duration.toMinutes();
        Long seconds = duration.minusMinutes(minutes).getSeconds();

        return minutes + "min " + seconds "sec"
}
Indifferentism answered 14/11, 2018 at 11:23 Comment(0)
N
3

I don't think Java 1.5 support concurrent TimeUnit. Otherwise, I would suggest for TimeUnit. Below is based on pure math approach.

stopWatch.stop();
long milliseconds = stopWatch.getTime();

int seconds = (int) ((milliseconds / 1000) % 60);
int minutes = (int) ((milliseconds / 1000) / 60);
Nosing answered 28/1, 2016 at 17:57 Comment(0)
H
1

You can easily convert miliseconds into seconds, minutes and hours.

                val millis = **milliSecondsYouWantToConvert**
                val seconds = (millis / 1000) % 60
                val minutes = ((millis / 1000) / 60) % 60
                val hours = ((millis / 1000) / 60) / 60

                println("--------------------------------------------------------------------")
                println(String.format("%02dh : %02dm : %02ds remaining", hours, minutes, seconds))
                println("--------------------------------------------------------------------")
**RESULT :** 
--------------------------------------------------------------------
  01h : 23m : 37s remaining
--------------------------------------------------------------------

Hortense answered 16/10, 2019 at 7:38 Comment(0)
Y
1

Below code does the work for converting ms to min:secs with [m:ss] format

int seconds;
int minutes;
String Sec;
long Mills = ...;  // Milliseconds goes here
minutes = (int)(Mills / 1000)  / 60;
seconds = (int)((Mills / 1000) % 60);
Sec = seconds+"";

TextView.setText(minutes+":"+Sec);//Display duration [3:40]
Yu answered 7/12, 2019 at 8:27 Comment(0)
M
1

You can convert milliseconds to hours, minutes and seconds using this method

public String timeConversion(Long millie) {
    if (millie != null) {
        long seconds = (millie / 1000);
        long sec = seconds % 60;
        long min = (seconds / 60) % 60;
        long hrs = (seconds / (60 * 60)) % 24;
        if (hrs > 0) {
            return String.format("%02d:%02d:%02d", hrs, min, sec);
        } else {
            return String.format("%02d:%02d", min, sec);
        }
    } else {
        return null;
    }
}

then use this method like this

videoDuration.setText(timeConversion((long) milliSecondsHere));

In Kotlin

fun timeConverter(millie: Long): String {
return run {
    val seconds: Long = millie / 2000
    val sec = seconds % 60
    val min = seconds / 60 % 60
    val hrs = seconds / (60 * 60) % 24
    return if (hrs > 0) {
        String.format("%02d:%02d:%02d", hrs, min, sec)
    } else {
        String.format("%02d:%02d", min, sec)
    }
}
Mensal answered 18/6, 2022 at 18:50 Comment(0)
J
0
package com.v3mobi.userpersistdatetime;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class UserActivity extends AppCompatActivity {

    Date startDate;
    Date endDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
        startDate = java.util.Calendar.getInstance().getTime(); //set your start time
    }

    @Override
    protected void onStop() {
        super.onStop();
        endDate = java.util.Calendar.getInstance().getTime(); // set  your end time

        chekUserPersistence();

    }

    private void chekUserPersistence()
    {
        long duration = endDate.getTime() - startDate.getTime();
//        long duration = 301000;

        long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);         // minutes ok
        long secs = (duration/1000) % 60;         // minutes ok


        Toast.makeText(UserActivity.this, "Diff  "
                +  diffInMinutes + " : "+ secs , Toast.LENGTH_SHORT).show();

        System.out.println("Diff  " + diffInMinutes +" : "+ secs );

        Log.e("keshav","diffInMinutes -->" +diffInMinutes);
        Log.e("keshav","secs -->" +secs);
        finish();
    }
}
Janik answered 3/5, 2019 at 14:24 Comment(0)
T
0

Apache Commons Lang class DurationFormatUtils. This class has some standard formats out of the box but also supports custom formats.

String result = DurationFormatUtils.formatDuration(millis, "mm:ss.SSS' sec.'");
Teal answered 23/8, 2021 at 14:38 Comment(0)
P
0

You can use the following code to get seconds and minutes from the miliseconds

    fun main() {
    val mili = 150000
    val min = mili/1000/60
    val sec: Double = (mili.toDouble()/60000.0 - 2.0) * 60
    println(mili)
    println(min)
    println(sec)
   }
Panga answered 31/3 at 14:38 Comment(0)
D
-2

Here is a simple solution. Example calls that could be used in any method:

  • StopWatch.start();
  • StopWatch.stop();
  • StopWatch.displayDiff(); displays difference in minutes and seconds between start and stop. (elapsed time)

    import java.time.Duration;
    import java.time.Instant;
    
    
    public class StopWatch {
    
        private static Instant start;
        private static Instant stop;
    
        private void StopWatch() {
            // not called
        }
    
        public static void start() {
            start = Instant.now();
        }
    
        public static void stop() {
            stop = Instant.now();
        }
    
        public static void displayDiff() {
            Duration totalTime = Duration.between(start, stop);
            System.out.println(totalTime.toMinutes() + " Minutes " 
                               + totalTime.toMillis() / 1000 + " Seconds");
        }
    }
    
Disproportion answered 17/12, 2016 at 17:9 Comment(1)
Incorrect. The toMillis method reports the entire duration as milliseconds.Tonguetied
T
-2

This is related to a previous post, but in my opinion the solution proposed wasn't quite right.
In order to realize a correct conversion, this is what should be implemnted:

long time_millis = 1926546
int minutes = time_millis / 1000 / 60
int seconds = ((int)(time_millis / 1000) % 60) #important that this division is cast to an int

println "Build time: $minutes minutes $seconds seconds"
Tahoe answered 29/4, 2021 at 15:6 Comment(1)
I am glad you want to help with providing a solution to a problem. However, needs to be improved. Possible, you should format the code properly, plus you can link to the question you want to correct. Moreove, are you sure that this is Java? Please tag the language you are using.Suppurate

© 2022 - 2024 — McMap. All rights reserved.