How do I get milliseconds to hours, minutes, secs and remaining millisecs - java

Ok, so I've recently started programming in java about a week ago, and I'm attempting to write a program that will take milliseconds and give me hours, minutes, seconds, and remaining milliseconds. Now I've got most of it down its just for some reason, giving me numbers that are off. I should be getting 2hrs, 46 min, 40 seconds, and 123 milliseconds. But instead I'm getting 2hrs, 2min, 3secs, and 123 milliseconds.
Heres my code
int beginning = 10000123; //beginning is the starting number of milli seconds
int hours = beginning/3600000;
int rSecs = beginning%1000; //r = remaining
int minutes = rSecs/60;
int seconds = rSecs%60;
int milliSecs = rSecs%1000;
System.out.println("Lab03, 100 Point Version\n");
System.out.println("Starting Milliseconds" + beginning);
System.out.println("Hours:" + hours);
System.out.println("Minutes:" + minutes);
System.out.println("Seconds:" + seconds);
System.out.println("Milli Seconds:" + milliSecs);
Thanks for any and all help!

You need to modulo by 3600000 for remaining milli second
int hours = beginning/3600000;
int rMiliSecs = beginning%3600000;
Since it millisecond you need to divide by 60000(1m-> 60s -> 60000ms) for minute and modulo by 60000 to get remainings
int minutes = rMiliSecs/60000;
rMiliSecs = rMiliSecs%60000;
Then divide by 1000 for the second and modulo by 1000(1s -> 1000ms) for remaining millisecond
int seconds = rMiliSecs/1000;
int milliSecs = rMiliSecs%1000;

If you want to avoid the magic numbers and do a more OO approach you can use the Duration class.
Duration duration = Duration.ofMillis(10000123);
long hours = duration.toHours();
duration = duration.minusHours(hours);
long minutes = duration.toMinutes();
duration = duration.minusMinutes(minutes);
long seconds = duration.getSeconds();
duration = duration.minusSeconds(seconds);
long milliSec = duration.toMillis();

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.

Convert time to seconds and then convert it back to hours (JAVA)

I've been working on assignment for my homework and I'm stuck again. It's very simple task. (I think so)
For example I have 2493 seconds.
I want to convert it to this format 00:41:33
I know I could use java.utilities but simple maths could solve it too(?)
if(Time>3600) {
Hours = Time/3600;
}
if(Time<3600)
{
Hours = 0;
}
Minutes = ((Time-(3600*Hours))/60);
Seconds = ??????????;
So the only thing I don't get how do I get to know how many seconds left from this thing?
If your Time is given in seconds, you can do the following for your calculation:
int hours = Time / 3600;
int minutes = (Time % 3600) / 60;
int seconds = Time % 60;
The modulus operator gives the remainder after division, and can be used to calculate minutes and seconds.
To calculate minutes, we want to remove all time over 1 hour, so we mod Time by 3600, then we divide by 60.
To calculate seconds, because Time is already in seconds, we mod Time by 60.
Here's the general formula for convertions like this. You do have to remember to subtract the values you have previously converted. For example, after you calculate the hours, you have to subtract the hours so you can then convert the minutes.
public class TimeConverstion
{
private static void convert( int i )
{
int hours = i / 3600;
i = i - hours * 3600;
int minutes = i / 60;
i = i - minutes * 60;
int seconds = i;
System.out.printf( "Hours:%d, minutes:%d, seconds%d%n", hours, minutes,
seconds );
}
public static void main(String[] args) {
convert( 149580 );
}
}
Output of this program:
run:
Hours:41, minutes:33, seconds0
BUILD SUCCESSFUL (total time: 0 seconds)

Getting minutes from 24 hour time? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I will start with an example: time is 20:00 (2000) and I want to find how many minutes its been since 09:00 (0900), I tried using mod of 60 but this gave me an off time.
Example:
Elapsed time between 1610 1700
1700-1610 = 90, this is obviously wrong
(1700-1610)%60 = 30,
90-30 equals 60, but the answer should be 50. I'm very confused with what I should be doing, how would I go about dealing with this in java? Thanks!
Convert hours to minutes.
1700 hours = 17*60 minutes
1610 hours = 16*60 minutes + 10 minutes
to find out the difference, simple subtraction will do the job
17*60 - 16*60 - 10
Update:
Assuming user enters in 0000 (hhmm) format, you can simply split by size
//psuedo code
String data = userInput;
int hours = Integer.parseInt(data.split(0,2));
int mins = Intger.parseInt(data.split(2,4));
You mixing two representations of the time
13:50
1350 (minutes)
13:50 is 13 hours and 50 minutes, but 1350 is 1350/60 = 22 hours and 1350%60 = 30 minutes
Before you can add, subtract, multiply or divide time you have to convert it to number. In your case:
Elapsed time between 16:10 17:00
16:10 = 16*60+10 = 970
17:00 = 17*60+00 = 1020
17:00 - 16:10 = 1020 - 970 = 50
In Java you could write:
public int minutesFromTime(String time) {
String [] parts = time.split(":");
int hours = Integer.parseInt(parts[0]);
int minutes = Integer.parseInt(parts[1]);
return hours * 60 + minutes;
}
Then
System.out.println("Difference is "
+ (minutesFromTime("17:00") - minutesFromTime("16:10"))
+ " minutes");
To convert your 24-hour time to minutes you need to determine hours and minutes:
int hours = time / 100;
int minutes = time % 100;
And then calculate minutes since midnight:
int minutesSinceMidnight = (hours * 60) + minutes;
You can subtract the minutesSinceMidnight for both times to arrive at the time difference in minutes.
This simple example should do the job:
public static void main(String[] args) {
String after = "2000";
String before = "0900";
int hours = (parseInt(after) - parseInt(before)) / 100;
int minutes = (parseInt(after) % 100) - (parseInt(before) % 100) % 60;
if (minutes < 0) minutes += 60;
System.out.printf("Minutes passed from %s to %s are %d\n", before, after, hours * 60 + minutes);
}
you are dealing with time (60 min), so you can't directly use the math functions (10 base).
So I suggest that you convert your data to Date and then deal with it.
DateFormat dateFormat = new SimpleDateFormat( "HHmm");
Date date = dateFormat.parse("1610");
Date date2 = dateFormat.parse("1700");
long diff = date2.getTime() - date.getTime();
long diffMinutes = diff / (60 * 1000);
You can't do it like this, you are confusing hour and minute as the same unit in your way to do this.
You should separate hour and minute to get the good answer
for example:
String time1 = "1700";
int hour1 = Integer.parseInt(time1.substring(0,2));
int minute1 = Integer.parseInt(time1.substring(2,4));
From int to String to parse
int timeInt = 1715;
String time1 = ""+timeInt;
int hour1 = Integer.parseInt(time1.substring(0,2));
int minute1 = Integer.parseInt(time1.substring(2,4));
Or staying in int
int timeInt = 1715;
int hour = timeInt / 100;
int min = timeInt - hour*100;
If we assume user will always input in XXXX (hhmm) format you can try using this code:
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter first time value: ");
int firstTime = userInput.nextInt();
System.out.print("Enter second time value: ");
int secondTime = userInput.nextInt();
int hoursFirst = (int)(firstTime/100);
int minutesFirst = firstTime%100;
int hoursSecond = (int)(secondTime/100);
int minutesSecond = secondTime%100;
int difference = Math.abs((hoursSecond - hoursFirst - 1) * 60 + (60 - minutesFirst) + minutesSecond);
System.out.println("Difference between " + hoursFirst + ":" + minutesFirst
+ " and " + hoursSecond + ":" + minutesSecond + " is " + difference + " minutes.");
}
Output example:
Enter first time value: 1820
Enter second time value: 1610
Difference between 18:20 and 16:10 is 130 minutes.

Converting Milliseconds to Minutes and Seconds?

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

Categories

Resources