Converting Milliseconds to Minutes and Seconds? - java

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.

I would suggest using TimeUnit. You can use it like this:
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);

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

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?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

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

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;

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

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.

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.

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.

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

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

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

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

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

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]

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

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

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.'");

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"

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

Related

How to convert Milliseconds to Minutes and Seconds [duplicate]

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.
I would suggest using TimeUnit. You can use it like this:
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
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);
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?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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;
}
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;
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
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.
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.
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.
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);
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
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"
}
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);
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
--------------------------------------------------------------------
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]
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)
}
}
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();
}
}
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.'");
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"
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");
}
}

How do I get difference between two dates in android with millisec?

My SimpleDateFormat format is "HH:mm:ss.SSS"
My example time: "00:01:20.442"
How to get (extract) milliseconds 442 to string?
I found code:
long diff = date1.getTime() - date2.getTime();
long mseconds = ?????????;
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
System.out.println("Milliseconds : "+ String.valueOf(mseconds));
P.S. I'm use API 19 (Adroid 4.4.2)
You take the remainder of dividing by 1000, using the remainder operator:
long mseconds = diff % 1000;
But note that the milliseconds value you've asked for (442) doesn't match what you're doing to get seconds, minutes, etc. In seconds, you'll get the total number of seconds between the dates, which could be in the hundreds of thousands depending on the dates, not just 0-59.
If the goal is to get days, hours (within the day), minutes (within the hour), etc., then:
long mseconds = diff % 1000;
long seconds = (diff / 1000) % 60;
long minutes = (seconds / 60) % 60;
long hours = (minutes / 60) % 24;
long days = hours / 24;
Using the Joda Time library (which in my opinion should be in every project that uses time):
final long millis = DateTime.parse("00:01:20.442", DateTimeFormat.forPattern("HH:mm:ss.SSS")).getMillisOfSecond();
assertEquals(442, millis);
Or, if you want all of them:
final DateTime dt = DateTime.parse("00:01:20.442", DateTimeFormat.forPattern("HH:mm:ss.SSS"));
final long millis = dt.getMillisOfSecond(); //442
final long second = dt.getSecondOfMinute(); //20
final long min = dt.getMinuteOfHour(); //1
final long hour = dt.getHourOfDay(); //0
Why don't you simply split the String by . and use the second element?
Like:
long millis = Long.parseLong(dateStr.split(".")[1]);
Where dateStr is a String of form HH:mm:ss.SSS.
It is much better solution than using a 3rd party library for simple task.

Milliseconds to Hours(more than 24)

I have a system that sum up all the hours(converted to milliseconds), if that hour is more than 24 hours(eg, 26 hours), it will back to 02:00:00 instead of 26:00:00.
totH = parser.parse(totalH);
totHTotal += totH.getTime(); // assume totHTotal gets 93600000.
totalHours = parser.format(new Date(totHTotal));
System.out.println(totalHours); // this will output 02:00:00 but I want this to output 26:00:00.
Can somebody help me, thank you.
You could use a Duration or do the arithmetic.
1 hour: 3 600 000ms
1 minute: 60 000ms
1 second: 1 000ms
You can run it here: https://repl.it/GLLH/9
import java.time.Duration;
class Main {
public static void main(String[] args) {
System.out.println("Using math");
long millsMath = 93631000;
long hoursMath = millsMath / 3600000;
long minutesMath = (millsMath % 3600000) / 60000;
long secondsMath = (millsMath % 60000) / 1000;
String outMath = String.format("%02d:%02d:%02d",hoursMath, minutesMath, secondsMath);
System.out.println(outMath);
System.out.println("\nUsing Duration");
Duration dur = Duration.ofMillis(93631000);
long hoursDur = dur.toHours();
long minutesDur = dur.minusHours(hoursDur).toMinutes();
long secondsDur = dur.minusHours(hoursDur).minusMinutes(minutesDur).getSeconds();
String outDur = String.format("%02d:%02d:%02d", hoursDur, minutesDur, secondsDur);
System.out.println(outDur);
}
}
output:
Using math
26:00:31
Using Duration
26:00:31

How can I convert elapsed milliseconds stored in a long to a String formatted to mm:ss.ss in Java?

I have a variable currTime computed in the following way:
long currTime = System.currentTimeMillis() - start; //where start is the start time of whatever I'm timing
How do I convert this to a String for display such that for example:
12544 will display as "00:12.54"
67855 will display as "01:07.86"
...so on and so forth...?
The easiest, I think, is to do it by hand:
public String elapsedToString(long elapsedTimeMillis) {
long seconds = (elapsedTimeMillis + 500) / 1000; // round
long minutes = seconds / 60;
long hours = minutes / 60;
return String.format("%1$02d:%2$02d:%3$02d",
hours,
minutes % 60,
seconds % 60);
}
Oops. You wanted mm:ss.ss
public String elapsedToString(long elapsedTimeMillis) {
long hundredths = (elapsedTimeMillis + 5) / 10; // round
long seconds = hundredths / 100;
long minutes = seconds / 60;
return String.format("%1$02d:%2$02d.%3$02d",
minutes,
seconds % 60,
hundredths % 100);
}
A solution for three digit milliseconds is very easy:
public String formatDuration(long elapsedTimeMillis) {
SimpleDateFormat df = new java.text.SimpleDateFormat("mm:ss.SSS");
df.setTimeZone(TimeZone.getTimeZone("UTC")); // Epoch is UTC
return df.format(new Date(elapsedTimeMillis));
}
For two digit milliseconds, one has to use Joda Time formatter, remove the final digit from the string or go for a manual solution.
See:
Java DateFormat for 2 millisecond precision

How to convert Milliseconds to "X mins, x seconds" in Java?

I want to record the time using System.currentTimeMillis() when a user begins something in my program. When he finishes, I will subtract the current System.currentTimeMillis() from the start variable, and I want to show them the time elapsed using a human readable format such as "XX hours, XX mins, XX seconds" or even "XX mins, XX seconds" because its not likely to take someone an hour.
What's the best way to do this?
Use the java.util.concurrent.TimeUnit class:
String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
Note: TimeUnit is part of the Java 1.5 specification, but toMinutes was added as of Java 1.6.
To add a leading zero for values 0-9, just do:
String.format("%02d min, %02d sec",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
If TimeUnit or toMinutes are unsupported (such as on Android before API version 9), use the following equations:
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);
//etc...
Based on #siddhadev's answer, I wrote a function which converts milliseconds to a formatted string:
/**
* Convert a millisecond duration to a string format
*
* #param millis A duration to convert to a string form
* #return A string of the form "X Days Y Hours Z Minutes A Seconds".
*/
public static String getDurationBreakdown(long millis) {
if(millis < 0) {
throw new IllegalArgumentException("Duration must be greater than zero!");
}
long days = TimeUnit.MILLISECONDS.toDays(millis);
millis -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(millis);
millis -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
millis -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
StringBuilder sb = new StringBuilder(64);
sb.append(days);
sb.append(" Days ");
sb.append(hours);
sb.append(" Hours ");
sb.append(minutes);
sb.append(" Minutes ");
sb.append(seconds);
sb.append(" Seconds");
return(sb.toString());
}
long time = 1536259;
return (new SimpleDateFormat("mm:ss:SSS")).format(new Date(time));
Prints:
25:36:259
Using the java.time package in Java 8:
Instant start = Instant.now();
Thread.sleep(63553);
Instant end = Instant.now();
System.out.println(Duration.between(start, end));
Output is in ISO 8601 Duration format: PT1M3.553S (1 minute and 3.553 seconds).
Uhm... how many milliseconds are in a second? And in a minute? Division is not that hard.
int seconds = (int) ((milliseconds / 1000) % 60);
int minutes = (int) ((milliseconds / 1000) / 60);
Continue like that for hours, days, weeks, months, year, decades, whatever.
I would not pull in the extra dependency just for that (division is not that hard, after all), but if you are using Commons Lang anyway, there are the DurationFormatUtils.
Example Usage (adapted from here):
import org.apache.commons.lang3.time.DurationFormatUtils
public String getAge(long value) {
long currentTime = System.currentTimeMillis();
long age = currentTime - value;
String ageString = DurationFormatUtils.formatDuration(age, "d") + "d";
if ("0d".equals(ageString)) {
ageString = DurationFormatUtils.formatDuration(age, "H") + "h";
if ("0h".equals(ageString)) {
ageString = DurationFormatUtils.formatDuration(age, "m") + "m";
if ("0m".equals(ageString)) {
ageString = DurationFormatUtils.formatDuration(age, "s") + "s";
if ("0s".equals(ageString)) {
ageString = age + "ms";
}
}
}
}
return ageString;
}
Example:
long lastTime = System.currentTimeMillis() - 2000;
System.out.println("Elapsed time: " + getAge(lastTime));
//Output: 2s
Note: To get millis from two LocalDateTime objects you can use:
long age = ChronoUnit.MILLIS.between(initTime, LocalDateTime.now())
Either hand divisions, or use the SimpleDateFormat API.
long start = System.currentTimeMillis();
// do your work...
long elapsed = System.currentTimeMillis() - start;
DateFormat df = new SimpleDateFormat("HH 'hours', mm 'mins,' ss 'seconds'");
df.setTimeZone(TimeZone.getTimeZone("GMT+0"));
System.out.println(df.format(new Date(elapsed)));
Edit by Bombe: It has been shown in the comments that this approach only works for smaller durations (i.e. less than a day).
Just to add more info
if you want to format like: HH:mm:ss
0 <= HH <= infinite
0 <= mm < 60
0 <= ss < 60
use this:
int h = (int) ((startTimeInMillis / 1000) / 3600);
int m = (int) (((startTimeInMillis / 1000) / 60) % 60);
int s = (int) ((startTimeInMillis / 1000) % 60);
I just had this issue now and figured this out
Shortest solution:
Here's probably the shortest which also deals with time zones.
System.out.printf("%tT", millis-TimeZone.getDefault().getRawOffset());
Which outputs for example:
00:18:32
Explanation:
%tT is the time formatted for the 24-hour clock as %tH:%tM:%tS.
%tT also accepts longs as input, so no need to create a Date. printf() will simply print the time specified in milliseconds, but in the current time zone therefore we have to subtract the raw offset of the current time zone so that 0 milliseconds will be 0 hours and not the time offset value of the current time zone.
Note #1: If you need the result as a String, you can get it like this:
String t = String.format("%tT", millis-TimeZone.getDefault().getRawOffset());
Note #2: This only gives correct result if millis is less than a day because the day part is not included in the output.
I think the best way is:
String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toSeconds(length)/60,
TimeUnit.MILLISECONDS.toSeconds(length) % 60 );
Revisiting #brent-nash contribution, we could use modulus function instead of subtractions and use String.format method for the result string:
/**
* Convert a millisecond duration to a string format
*
* #param millis A duration to convert to a string form
* #return A string of the form "X Days Y Hours Z Minutes A Seconds B Milliseconds".
*/
public static String getDurationBreakdown(long millis) {
if (millis < 0) {
throw new IllegalArgumentException("Duration must be greater than zero!");
}
long days = TimeUnit.MILLISECONDS.toDays(millis);
long hours = TimeUnit.MILLISECONDS.toHours(millis) % 24;
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis) % 60;
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis) % 60;
long milliseconds = millis % 1000;
return String.format("%d Days %d Hours %d Minutes %d Seconds %d Milliseconds",
days, hours, minutes, seconds, milliseconds);
}
Joda-Time
Using Joda-Time:
DateTime startTime = new DateTime();
// do something
DateTime endTime = new DateTime();
Duration duration = new Duration(startTime, endTime);
Period period = duration.toPeriod().normalizedStandard(PeriodType.time());
System.out.println(PeriodFormat.getDefault().print(period));
For those who looking for Kotlin code:
fun converter(millis: Long): String =
String.format(
"%02d : %02d : %02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millis)
),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millis)
)
)
Sample output: 09 : 10 : 26
My simple calculation:
String millisecToTime(int millisec) {
int sec = millisec/1000;
int second = sec % 60;
int minute = sec / 60;
if (minute >= 60) {
int hour = minute / 60;
minute %= 60;
return hour + ":" + (minute < 10 ? "0" + minute : minute) + ":" + (second < 10 ? "0" + second : second);
}
return minute + ":" + (second < 10 ? "0" + second : second);
}
Happy coding :)
Firstly, System.currentTimeMillis() and Instant.now() are not ideal for timing. They both report the wall-clock time, which the computer doesn't know precisely, and which can move erratically, including going backwards if for example the NTP daemon corrects the system time. If your timing happens on a single machine then you should instead use System.nanoTime().
Secondly, from Java 8 onwards java.time.Duration is the best way to represent a duration:
long start = System.nanoTime();
// do things...
long end = System.nanoTime();
Duration duration = Duration.ofNanos(end - start);
System.out.println(duration); // Prints "PT18M19.511627776S"
System.out.printf("%d Hours %d Minutes %d Seconds%n",
duration.toHours(), duration.toMinutes() % 60, duration.getSeconds() % 60);
// prints "0 Hours 18 Minutes 19 Seconds"
for Android below API 9
(String.format("%d hr %d min, %d sec", millis/(1000*60*60), (millis%(1000*60*60))/(1000*60), ((millis%(1000*60*60))%(1000*60))/1000))
For small times, less than an hour, I prefer:
long millis = ...
System.out.printf("%1$TM:%1$TS", millis);
// or
String str = String.format("%1$TM:%1$TS", millis);
for longer intervalls:
private static final long HOUR = TimeUnit.HOURS.toMillis(1);
...
if (millis < HOUR) {
System.out.printf("%1$TM:%1$TS%n", millis);
} else {
System.out.printf("%d:%2$TM:%2$TS%n", millis / HOUR, millis % HOUR);
}
Here is an answer based on Brent Nash answer, Hope that helps !
public static String getDurationBreakdown(long millis)
{
String[] units = {" Days ", " Hours ", " Minutes ", " Seconds "};
Long[] values = new Long[units.length];
if(millis < 0)
{
throw new IllegalArgumentException("Duration must be greater than zero!");
}
values[0] = TimeUnit.MILLISECONDS.toDays(millis);
millis -= TimeUnit.DAYS.toMillis(values[0]);
values[1] = TimeUnit.MILLISECONDS.toHours(millis);
millis -= TimeUnit.HOURS.toMillis(values[1]);
values[2] = TimeUnit.MILLISECONDS.toMinutes(millis);
millis -= TimeUnit.MINUTES.toMillis(values[2]);
values[3] = TimeUnit.MILLISECONDS.toSeconds(millis);
StringBuilder sb = new StringBuilder(64);
boolean startPrinting = false;
for(int i = 0; i < units.length; i++){
if( !startPrinting && values[i] != 0)
startPrinting = true;
if(startPrinting){
sb.append(values[i]);
sb.append(units[i]);
}
}
return(sb.toString());
}
long startTime = System.currentTimeMillis();
// do your work...
long endTime=System.currentTimeMillis();
long diff=endTime-startTime;
long hours=TimeUnit.MILLISECONDS.toHours(diff);
diff=diff-(hours*60*60*1000);
long min=TimeUnit.MILLISECONDS.toMinutes(diff);
diff=diff-(min*60*1000);
long seconds=TimeUnit.MILLISECONDS.toSeconds(diff);
//hour, min and seconds variables contains the time elapsed on your work
This is easier in Java 9:
Duration elapsedTime = Duration.ofMillis(millisDiff );
String humanReadableElapsedTime = String.format(
"%d hours, %d mins, %d seconds",
elapsedTime.toHours(),
elapsedTime.toMinutesPart(),
elapsedTime.toSecondsPart());
This produces a string like 0 hours, 39 mins, 9 seconds.
If you want to round to whole seconds before formatting:
elapsedTime = elapsedTime.plusMillis(500).truncatedTo(ChronoUnit.SECONDS);
To leave out the hours if they are 0:
long hours = elapsedTime.toHours();
String humanReadableElapsedTime;
if (hours == 0) {
humanReadableElapsedTime = String.format(
"%d mins, %d seconds",
elapsedTime.toMinutesPart(),
elapsedTime.toSecondsPart());
} else {
humanReadableElapsedTime = String.format(
"%d hours, %d mins, %d seconds",
hours,
elapsedTime.toMinutesPart(),
elapsedTime.toSecondsPart());
}
Now we can have for example 39 mins, 9 seconds.
To print minutes and seconds with leading zero to make them always two digits, just insert 02 into the relevant format specifiers, thus:
String humanReadableElapsedTime = String.format(
"%d hours, %02d mins, %02d seconds",
elapsedTime.toHours(),
elapsedTime.toMinutesPart(),
elapsedTime.toSecondsPart());
Now we can have for example 0 hours, 39 mins, 09 seconds.
for correct strings ("1hour, 3sec", "3 min" but not "0 hour, 0 min, 3 sec") i write this code:
int seconds = (int)(millis / 1000) % 60 ;
int minutes = (int)((millis / (1000*60)) % 60);
int hours = (int)((millis / (1000*60*60)) % 24);
int days = (int)((millis / (1000*60*60*24)) % 365);
int years = (int)(millis / 1000*60*60*24*365);
ArrayList<String> timeArray = new ArrayList<String>();
if(years > 0)
timeArray.add(String.valueOf(years) + "y");
if(days > 0)
timeArray.add(String.valueOf(days) + "d");
if(hours>0)
timeArray.add(String.valueOf(hours) + "h");
if(minutes>0)
timeArray.add(String.valueOf(minutes) + "min");
if(seconds>0)
timeArray.add(String.valueOf(seconds) + "sec");
String time = "";
for (int i = 0; i < timeArray.size(); i++)
{
time = time + timeArray.get(i);
if (i != timeArray.size() - 1)
time = time + ", ";
}
if (time == "")
time = "0 sec";
If you know the time difference would be less than an hour, then you can use following code:
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c2.add(Calendar.MINUTE, 51);
long diff = c2.getTimeInMillis() - c1.getTimeInMillis();
c2.set(Calendar.MINUTE, 0);
c2.set(Calendar.HOUR, 0);
c2.set(Calendar.SECOND, 0);
DateFormat df = new SimpleDateFormat("mm:ss");
long diff1 = c2.getTimeInMillis() + diff;
System.out.println(df.format(new Date(diff1)));
It will result to: 51:00
This answer is similar to some answers above. However, I feel that it would be beneficial because, unlike other answers, this will remove any extra commas or whitespace and handles abbreviation.
/**
* Converts milliseconds to "x days, x hours, x mins, x secs"
*
* #param millis
* The milliseconds
* #param longFormat
* {#code true} to use "seconds" and "minutes" instead of "secs" and "mins"
* #return A string representing how long in days/hours/minutes/seconds millis is.
*/
public static String millisToString(long millis, boolean longFormat) {
if (millis < 1000) {
return String.format("0 %s", longFormat ? "seconds" : "secs");
}
String[] units = {
"day", "hour", longFormat ? "minute" : "min", longFormat ? "second" : "sec"
};
long[] times = new long[4];
times[0] = TimeUnit.DAYS.convert(millis, TimeUnit.MILLISECONDS);
millis -= TimeUnit.MILLISECONDS.convert(times[0], TimeUnit.DAYS);
times[1] = TimeUnit.HOURS.convert(millis, TimeUnit.MILLISECONDS);
millis -= TimeUnit.MILLISECONDS.convert(times[1], TimeUnit.HOURS);
times[2] = TimeUnit.MINUTES.convert(millis, TimeUnit.MILLISECONDS);
millis -= TimeUnit.MILLISECONDS.convert(times[2], TimeUnit.MINUTES);
times[3] = TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS);
StringBuilder s = new StringBuilder();
for (int i = 0; i < 4; i++) {
if (times[i] > 0) {
s.append(String.format("%d %s%s, ", times[i], units[i], times[i] == 1 ? "" : "s"));
}
}
return s.toString().substring(0, s.length() - 2);
}
/**
* Converts milliseconds to "x days, x hours, x mins, x secs"
*
* #param millis
* The milliseconds
* #return A string representing how long in days/hours/mins/secs millis is.
*/
public static String millisToString(long millis) {
return millisToString(millis, false);
}
There is a problem. When milliseconds is 59999, actually it is 1 minute but it will be computed as 59 seconds and 999 milliseconds is lost.
Here is a modified version based on previous answers, which can solve this loss:
public static String formatTime(long millis) {
long seconds = Math.round((double) millis / 1000);
long hours = TimeUnit.SECONDS.toHours(seconds);
if (hours > 0)
seconds -= TimeUnit.HOURS.toSeconds(hours);
long minutes = seconds > 0 ? TimeUnit.SECONDS.toMinutes(seconds) : 0;
if (minutes > 0)
seconds -= TimeUnit.MINUTES.toSeconds(minutes);
return hours > 0 ? String.format("%02d:%02d:%02d", hours, minutes, seconds) : String.format("%02d:%02d", minutes, seconds);
}
I have covered this in another answer but you can do:
public static Map<TimeUnit,Long> computeDiff(Date date1, Date date2) {
long diffInMillies = date2.getTime() - date1.getTime();
List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));
Collections.reverse(units);
Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>();
long milliesRest = diffInMillies;
for ( TimeUnit unit : units ) {
long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
long diffInMilliesForUnit = unit.toMillis(diff);
milliesRest = milliesRest - diffInMilliesForUnit;
result.put(unit,diff);
}
return result;
}
The output is something like Map:{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0}, with the units ordered.
It's up to you to figure out how to internationalize this data according to the target locale.
DurationFormatUtils.formatDurationHMS(long)
I modified #MyKuLLSKI 's answer and added plurlization support. I took out seconds because I didn't need them, though feel free to re-add it if you need it.
public static String intervalToHumanReadableTime(int intervalMins) {
if(intervalMins <= 0) {
return "0";
} else {
long intervalMs = intervalMins * 60 * 1000;
long days = TimeUnit.MILLISECONDS.toDays(intervalMs);
intervalMs -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(intervalMs);
intervalMs -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(intervalMs);
StringBuilder sb = new StringBuilder(12);
if (days >= 1) {
sb.append(days).append(" day").append(pluralize(days)).append(", ");
}
if (hours >= 1) {
sb.append(hours).append(" hour").append(pluralize(hours)).append(", ");
}
if (minutes >= 1) {
sb.append(minutes).append(" minute").append(pluralize(minutes));
} else {
sb.delete(sb.length()-2, sb.length()-1);
}
return(sb.toString());
}
}
public static String pluralize(long val) {
return (Math.round(val) > 1 ? "s" : "");
}
Use java.util.concurrent.TimeUnit, and use this simple method:
private static long timeDiff(Date date, Date date2, TimeUnit unit) {
long milliDiff=date2.getTime()-date.getTime();
long unitDiff = unit.convert(milliDiff, TimeUnit.MILLISECONDS);
return unitDiff;
}
For example:
SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
Date firstDate = sdf.parse("06/24/2017 04:30:00");
Date secondDate = sdf.parse("07/24/2017 05:00:15");
Date thirdDate = sdf.parse("06/24/2017 06:00:15");
System.out.println("days difference: "+timeDiff(firstDate,secondDate,TimeUnit.DAYS));
System.out.println("hours difference: "+timeDiff(firstDate,thirdDate,TimeUnit.HOURS));
System.out.println("minutes difference: "+timeDiff(firstDate,thirdDate,TimeUnit.MINUTES));
System.out.println("seconds difference: "+timeDiff(firstDate,thirdDate,TimeUnit.SECONDS));
This topic has been well covered, I just wanted to share my functions perhaps you can make use of these rather than importing an entire library.
public long getSeconds(ms) {
return (ms/1000%60);
}
public long getMinutes(ms) {
return (ms/(1000*60)%60);
}
public long getHours(ms) {
return ((ms/(1000*60*60))%24);
}

Categories

Resources