Convert seconds value to hours minutes seconds? - java

I've been trying to convert a value of seconds (in a BigDecimal variable) to a string in an editText like "1 hour 22 minutes 33 seconds" or something of the kind.
I've tried this:
String sequenceCaptureTime = "";
BigDecimal roundThreeCalc = new BigDecimal("0");
BigDecimal hours = new BigDecimal("0");
BigDecimal myremainder = new BigDecimal("0");
BigDecimal minutes = new BigDecimal("0");
BigDecimal seconds = new BigDecimal("0");
BigDecimal var3600 = new BigDecimal("3600");
BigDecimal var60 = new BigDecimal("60");
(I have a roundThreeCalc which is the value in seconds so I try to convert it here.)
hours = (roundThreeCalc.divide(var3600));
myremainder = (roundThreeCalc.remainder(var3600));
minutes = (myremainder.divide(var60));
seconds = (myremainder.remainder(var60));
sequenceCaptureTime = hours.toString() + minutes.toString() + seconds.toString();
Then I set the editText to sequnceCaptureTime String.
But that didn't work. It force closed the app every time. I am totally out of my depth here, any help is greatly appreciated.

Is it necessary to use a BigDecimal? If you don't have to, I'd use an int or long for seconds, and it would simplify things a little bit:
hours = totalSecs / 3600;
minutes = (totalSecs % 3600) / 60;
seconds = totalSecs % 60;
timeString = String.format("%02d:%02d:%02d", hours, minutes, seconds);
You might want to pad each to make sure they're two digit values(or whatever) in the string, though.

DateUtils.formatElapsedTime(long), formats an elapsed time in the form "MM:SS" or "H:MM:SS" . It returns the String you are looking for. You can find the documentation here

You should have more luck with
hours = roundThreeCalc.divide(var3600, BigDecimal.ROUND_FLOOR);
myremainder = roundThreeCalc.remainder(var3600);
minutes = myremainder.divide(var60, BigDecimal.ROUND_FLOOR);
seconds = myremainder.remainder(var60);
This will drop the decimal values after each division.
Edit: If that didn't work, try this. (I just wrote and tested it)
public static int[] splitToComponentTimes(BigDecimal biggy)
{
long longVal = biggy.longValue();
int hours = (int) longVal / 3600;
int remainder = (int) longVal - hours * 3600;
int mins = remainder / 60;
remainder = remainder - mins * 60;
int secs = remainder;
int[] ints = {hours , mins , secs};
return ints;
}

Something really helpful in Java 8
import java.time.LocalTime;
private String ConvertSecondToHHMMSSString(int nSecondTime) {
return LocalTime.MIN.plusSeconds(nSecondTime).toString();
}

Here is the working code:
private String getDurationString(int seconds) {
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
seconds = seconds % 60;
return twoDigitString(hours) + " : " + twoDigitString(minutes) + " : " + twoDigitString(seconds);
}
private String twoDigitString(int number) {
if (number == 0) {
return "00";
}
if (number / 10 == 0) {
return "0" + number;
}
return String.valueOf(number);
}

I prefer java's built in TimeUnit library
long seconds = TimeUnit.MINUTES.toSeconds(8);

private String ConvertSecondToHHMMString(int secondtTime)
{
TimeZone tz = TimeZone.getTimeZone("UTC");
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
df.setTimeZone(tz);
String time = df.format(new Date(secondtTime*1000L));
return time;
}

This is my simple solution:
String secToTime(int sec) {
int seconds = sec % 60;
int minutes = sec / 60;
if (minutes >= 60) {
int hours = minutes / 60;
minutes %= 60;
if( hours >= 24) {
int days = hours / 24;
return String.format("%d days %02d:%02d:%02d", days,hours%24, minutes, seconds);
}
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
return String.format("00:%02d:%02d", minutes, seconds);
}
Test Results:
Result: 00:00:36 - 36
Result: 01:00:07 - 3607
Result: 6313 days 12:39:05 - 545488745

If you want the units h, min and sec for a duration you can use this:
public static String convertSeconds(int seconds) {
int h = seconds/ 3600;
int m = (seconds % 3600) / 60;
int s = seconds % 60;
String sh = (h > 0 ? String.valueOf(h) + " " + "h" : "");
String sm = (m < 10 && m > 0 && h > 0 ? "0" : "") + (m > 0 ? (h > 0 && s == 0 ? String.valueOf(m) : String.valueOf(m) + " " + "min") : "");
String ss = (s == 0 && (h > 0 || m > 0) ? "" : (s < 10 && (h > 0 || m > 0) ? "0" : "") + String.valueOf(s) + " " + "sec");
return sh + (h > 0 ? " " : "") + sm + (m > 0 ? " " : "") + ss;
}
int seconds = 3661;
String duration = convertSeconds(seconds);
That's a lot of conditional operators. The method will return those strings:
0 -> 0 sec
5 -> 5 sec
60 -> 1 min
65 -> 1 min 05 sec
3600 -> 1 h
3601 -> 1 h 01 sec
3660 -> 1 h 01
3661 -> 1 h 01 min 01 sec
108000 -> 30 h

I like to keep things simple therefore:
int tot_seconds = 5000;
int hours = tot_seconds / 3600;
int minutes = (tot_seconds % 3600) / 60;
int seconds = tot_seconds % 60;
String timeString = String.format("%02d Hour %02d Minutes %02d Seconds ", hours, minutes, seconds);
System.out.println(timeString);
The result will be: 01 Hour 23 Minutes 20 Seconds

Duration from java.time
BigDecimal secondsValue = BigDecimal.valueOf(4953);
if (secondsValue.compareTo(BigDecimal.valueOf(Long.MAX_VALUE)) > 0) {
System.out.println("Seconds value " + secondsValue + " is out of range");
} else {
Duration dur = Duration.ofSeconds(secondsValue.longValueExact());
long hours = dur.toHours();
int minutes = dur.toMinutesPart();
int seconds = dur.toSecondsPart();
System.out.format("%d hours %d minutes %d seconds%n", hours, minutes, seconds);
}
Output from this snippet is:
1 hours 22 minutes 33 seconds
If there had been a non-zero fraction of second in the BigDecimal this code would not have worked as it stands, but you may be able to modify it. The code works in Java 9 and later. In Java 8 the conversion from Duration into hours minutes and seconds is a bit more wordy, see the link at the bottom for how. I am leaving to you to choose the correct singular or plural form of the words (hour or hours, etc.).
Links
Oracle tutorial: Date Time explaining how to use java.time.
Answer by lauhub showing the conversion from a Duration to days, hours, minutes and seconds in Java 8.

This Code Is working Fine :
txtTimer.setText(String.format("%02d:%02d:%02d",(SecondsCounter/3600), ((SecondsCounter % 3600)/60), (SecondsCounter % 60)));

A nice and easy way to do it using GregorianCalendar
Import these into the project:
import java.util.GregorianCalendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Scanner;
And then:
Scanner s = new Scanner(System.in);
System.out.println("Seconds: ");
int secs = s.nextInt();
GregorianCalendar cal = new GregorianCalendar(0,0,0,0,0,secs);
Date dNow = cal.getTime();
SimpleDateFormat ft = new SimpleDateFormat("HH 'hours' mm 'minutes' ss 'seconds'");
System.out.println("Your time: " + ft.format(dNow));

for just minutes and seconds use this
String.format("%02d:%02d", (seconds / 3600 * 60 + ((seconds % 3600) / 60)), (seconds % 60))

With Java 8, you can easily achieve time in String format from long seconds like,
LocalTime.ofSecondOfDay(86399L)
Here, given value is max allowed to convert (upto 24 hours) and result will be
23:59:59
Pros : 1) No need to convert manually and to append 0 for single digit
Cons : work only for up to 24 hours

I use this:
public String SEG2HOR( long lnValue) { //OK
String lcStr = "00:00:00";
String lcSign = (lnValue>=0 ? " " : "-");
lnValue = lnValue * (lnValue>=0 ? 1 : -1);
if (lnValue>0) {
long lnHor = (lnValue/3600);
long lnHor1 = (lnValue % 3600);
long lnMin = (lnHor1/60);
long lnSec = (lnHor1 % 60);
lcStr = lcSign + ( lnHor < 10 ? "0": "") + String.valueOf(lnHor) +":"+
( lnMin < 10 ? "0": "") + String.valueOf(lnMin) +":"+
( lnSec < 10 ? "0": "") + String.valueOf(lnSec) ;
}
return lcStr;
}

Here's my function to address the problem:
public static String getConvertedTime(double time){
double h,m,s,mil;
mil = time % 1000;
s = time/1000;
m = s/60;
h = m/60;
s = s % 60;
m = m % 60;
h = h % 24;
return ((int)h < 10 ? "0"+String.valueOf((int)h) : String.valueOf((int)h))+":"+((int)m < 10 ? "0"+String.valueOf((int)m) : String.valueOf((int)m))
+":"+((int)s < 10 ? "0"+String.valueOf((int)s) : String.valueOf((int)s))
+":"+((int)mil > 100 ? String.valueOf((int)mil) : (int)mil > 9 ? "0"+String.valueOf((int)mil) : "00"+String.valueOf((int)mil));
}

I know this is pretty old but in java 8:
LocalTime.MIN.plusSeconds(120).format(DateTimeFormatter.ISO_LOCAL_TIME)

I use this in python to convert a float representing seconds to hours, minutes, seconds, and microseconds. It's reasonably elegant and is handy for converting to a datetime type via strptime to convert. It could also be easily extended to longer intervals (weeks, months, etc.) if needed.
def sectohmsus(seconds):
x = seconds
hmsus = []
for i in [3600, 60, 1]: # seconds in a hour, minute, and second
hmsus.append(int(x / i))
x %= i
hmsus.append(int(round(x * 1000000))) # microseconds
return hmsus # hours, minutes, seconds, microsecond

i have tried the best way and less code but may be it is little bit difficult to understand how i wrote my code but if you good at maths it is so easy
import java.util.Scanner;
class hours {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double s;
System.out.println("how many second you have ");
s =input.nextInt();
double h=s/3600;
int h2=(int)h;
double h_h2=h-h2;
double m=h_h2*60;
int m1=(int)m;
double m_m1=m-m1;
double m_m1s=m_m1*60;
System.out.println(h2+" hours:"+m1+" Minutes:"+Math.round(m_m1s)+" seconds");
}
}
more over it is accurate !

Tough there are yet many correct answers and an accepted one, if you want a more handmade and systematized way to do this, I suggest something like this:
/**
* Factors for converting seconds in minutes, minutes in hours, etc.
*/
private static int[] FACTORS = new int[] {
60, 60, 24, 7
};
/**
* Names of each time unit.
* The length of this array needs to be FACTORS.length + 1.
* The last one is the name of the remainder after
* obtaining each component.
*/
private static String[] NAMES = new String[] {
"second", "minute", "hour", "day", "week"
};
/**
* Checks if quantity is 1 in order to use or not the plural.
*/
private static String quantityToString(int quantity, String name) {
if (quantity == 1) {
return String.format("%d %s", quantity, name);
}
return String.format("%d %ss", quantity, name);
}
/**
* The seconds to String method.
*/
private static String secondsToString(int seconds) {
List<String> components = new ArrayList<>();
/**
* Obtains each component and stores only if is not 0.
*/
for (int i = 0; i < FACTORS.length; i++) {
int component = seconds % FACTORS[i];
seconds /= FACTORS[i];
if (component != 0) {
components.add(quantityToString(component, NAMES[i]));
}
}
/**
* The remainder is the last component.
*/
if (seconds != 0) {
components.add(quantityToString(seconds, NAMES[FACTORS.length]));
}
/**
* We have the non-0 components in reversed order.
* This could be extracted to another method.
*/
StringBuilder builder = new StringBuilder();
for (int i = components.size() - 1; i >= 0; i--) {
if (i == 0 && components.size() > 1) {
builder.append(" and ");
} else if (builder.length() > 0) {
builder.append(", ");
}
builder.append(components.get(i));
}
return builder.toString();
}
The result is as following:
System.out.println(secondsToString(5_000_000)); // 8 weeks, 1 day, 20 hours, 53 minutes and 20 seconds
System.out.println(secondsToString(500_000)); // 5 days, 18 hours, 53 minutes and 20 seconds
System.out.println(secondsToString(60*60*24)); // 1 day
System.out.println(secondsToString(2*60*60*24 + 3*60)); // 2 days and 3 minutes
System.out.println(secondsToString(60*60*24 + 3 * 60 * 60 + 53)); // 1 day, 3 hours and 53 seconds

You can get this done easily using method overloading.
Here's a code I wrote to convert seconds to hours, minutes and seconds format.
public class SecondsAndMinutes {
public static void main(String[] args) {
String finalOutput = getDurationString(-3666);
System.out.println(finalOutput);
}
public static String getDurationString(int seconds) {
if(seconds <= 0) {
return "Add a value bigger than zero.";
}else {
int hours = seconds / (60*60);
int remainingOneSeconds = seconds % (60*60);
int minutes = remainingOneSeconds / 60;
int remainingSeconds = remainingOneSeconds % 60;
String x = Integer.toString(hours);
return x+"h " + getDurationString(minutes, remainingSeconds);
}
}
public static String getDurationString(int minutes, int seconds) {
if(seconds <= 0 && seconds > 59) {
return "Seconds needs to be within 1 to 59";
}else {
String y = Integer.toString(minutes);
String z = Integer.toString(seconds);
return y+"m "+z+"s";
}
}
}

Related

how to get length of audio in minutes and seconds in android

int duration = mediaPlayer.getDuration();
textView = (TextView) findViewById(R.id.tvduration); textView.setText(duration);
From MediaPlayer:
the duration in milliseconds, if no duration is available (for
example, if streaming live content), -1 is returned.
That's why you will get from getDuration() the duration in milliseconds.
You can use this to get the time of MediaPlayer as String:
int duration = mediaPlayer.getDuration();
String time = String.format("%02d min, %02d sec",
TimeUnit.MILLISECONDS.toMinutes(duration),
TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration))
);
And then as you write in your question:
TextView textView = (TextView) findViewById(R.id.tvduration);
textView.setText(time);
public static String milliSecondsToTimer(long milliseconds) {
String finalTimerString = "";
String secondsString = "";
//Convert total duration into time
int hours = (int) (milliseconds / (1000 * 60 * 60));
int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
// Add hours if there
if (hours == 0) {
finalTimerString = hours + ":";
}
// Pre appending 0 to seconds if it is one digit
if (seconds == 10) {
secondsString = "0" + seconds;
} else {
secondsString = "" + seconds;
}
finalTimerString = finalTimerString + minutes + ":" + secondsString;
// return timer string
return finalTimerString;
}
It's 3 years old but nobody responded correctly then I gonna response
public String format(long millis) {
long allSeconds = millis / 1000;
int allMinutes;
byte seconds, minutes, hours;
if (allSeconds >= 60) {
allMinutes = (int) (allSeconds / 60);
seconds = (byte) (allSeconds % 60);
if (allMinutes >= 60) {
hours = (byte) (allMinutes / 60);
minutes = (byte) (allMinutes % 60);
return String.format(Locale.US, "%d:%d:" + formatSeconds(seconds), hours, minutes, seconds);
} else
return String.format(Locale.US, "%d:" + formatSeconds(seconds), allMinutes, seconds);
} else
return String.format(Locale.US, "0:" + formatSeconds((byte) allSeconds), allSeconds);
}
public String formatSeconds(byte seconds) {
String secondsFormatted;
if (seconds < 10) secondsFormatted = "0%d";
else secondsFormatted = "%d";
return secondsFormatted;
}
millis / 1000 convert millis to seconds. Example:
allSeconds = 68950 / 1000 = 68 seconds
If allSeconds are greater than 60, we will separate the minutes from seconds, then we will convert allSeconds = 68 to minutes using:
minutes = allSeconds / 60 = 1 left 8
The numbers that left will be the seconds
seconds = allSeconds % 60 = 8
The method formatSeconds(byte seconds) adds a zero whether the seconds are less than 10.
So in the end It will be: 1:08
Why bytes? Long has a bad perform, then it's better use bytes for longer operations.

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.

make a countdown timer

I want to make a countdown timer of New year from current time in android...
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,1);
thatDay.set(Calendar.MONTH,0); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 2014);
Calendar today = Calendar.getInstance();
long diff = thatDay.getTimeInMillis() - today.getTimeInMillis();
Now how to convert this diff into day,hour,minute,seconds format? please help
the following code
import java.util.Date;
import java.util.Calendar;
public class cal {
public static int SECONDS_IN_A_DAY = 24 * 60 * 60;
public static void main(String[] args) {
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(new Date(0)); /* reset */
thatDay.set(Calendar.DAY_OF_MONTH,1);
thatDay.set(Calendar.MONTH,0); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 2014);
Calendar today = Calendar.getInstance();
long diff = thatDay.getTimeInMillis() - today.getTimeInMillis();
long diffSec = diff / 1000;
long days = diffSec / SECONDS_IN_A_DAY;
long secondsDay = diffSec % SECONDS_IN_A_DAY;
long seconds = secondsDay % 60;
long minutes = (secondsDay / 60) % 60;
long hours = (secondsDay / 3600); // % 24 not needed
System.out.printf("%d days, %d hours, %d minutes and %d seconds\n", days, hours, minutes, seconds);
}
}
produces
27 days, 17 hours, 18 minutes and 2 seconds
27 days, 17 hours, 18 minutes and 1 seconds
27 days, 17 hours, 18 minutes and 0 seconds
27 days, 17 hours, 17 minutes and 59 seconds
27 days, 17 hours, 17 minutes and 58 seconds
27 days, 17 hours, 17 minutes and 57 seconds
27 days, 17 hours, 17 minutes and 56 seconds
27 days, 17 hours, 17 minutes and 55 seconds
27 days, 17 hours, 17 minutes and 54 seconds
27 days, 17 hours, 17 minutes and 53 seconds
hope this is what you want
Try this one
String formatStr = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf1 = new SimpleDateFormat(formatStr);
TimeZone obj = TimeZone.getTimeZone("CST");
sdf1.setTimeZone(obj);
Date date = sdf1.parse("your time"); // here put your time zone
long millis = date.getTime();
long currentTimeInMili = new Date().getTime();
MyCount counter = new MyCount(millis - currentTimeInMili, 1 * 1000);
counter.start();
class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}// MyCount
public void onPause() {
onPause();
}// finish
public void onTick(long millisUntilFinished) {
dynamicMatchDesTextView.setText(""+ formatTime(millisUntilFinished)+ " till match start");
}// on tick
#Override
public void onFinish() {
onStop();
}// finish
}
public String formatTime(long millis) {
String output = "00:00";
try {
long seconds = millis / 1000;
long minutes = seconds / 60;
long hours = seconds / 3600;
long days = seconds / (3600 * 24);
seconds = seconds % 60;
minutes = minutes % 60;
hours = hours % 24;
days = days % 30;
String sec = String.valueOf(seconds);
String min = String.valueOf(minutes);
String hur = String.valueOf(hours);
String day = String.valueOf(days);
if (seconds < 10)
sec = "0" + seconds;
if (minutes < 10)
min = "0" + minutes;
if (hours < 10)
hur = "0" + hours;
if (days < 10)
day = "0" + days;
output = day + "D " + hur + "H " + min + "M " + sec + "S";
} catch (Exception e) {
e.printStackTrace();
}
return output;
}
You can use this:
public String formatDate( long milliSec ) {
long diffSec = milliSec / (1000);
long diffMinutes = milliSec / (60 * 1000) % 60;
long diffHours = milliSec / (60 * 60 * 1000) % 24;
long diffDays = milliSec / (24 * 60 * 60 * 1000);
StringBuilder date = new StringBuilder();
if(diffDays != 0){
date.append(diffDays).append("D ");
}
if(diffHours != 0){
int length = (int)(Math.log10(diffHours)+1);
if(length == 1){
String s = "0"+diffHours;
date.append(s).append(":");
}else{
date.append(diffHours).append(":");
}
}else{
date.append("00").append(":");
}
if(diffMinutes != 0 ){
int length = (int)(Math.log10(diffMinutes)+1);
if(length == 1){
String s = "0"+diffMinutes;
date.append(s).append(":");
}else{
date.append(diffMinutes).append(":");;
}
}else{
date.append("00");
}
if(diffSec != 0){
int length = (int)(Math.log10(diffSec)+1);
if(length == 1){
String s = "0"+diffSec;
date.append(s);
}else{
date.append(diffSec);
}
}else{
date.append("00");
}
return date.toString();
}
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,1);
thatDay.set(Calendar.MONTH,0); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 2014);
thatDay.set(Calendar.HOUR_OF_DAY, 0);
thatDay.set(Calendar.MINUTE, 0);
System.out.println(thatDay.getTime());
Calendar today = Calendar.getInstance();
System.out.println(today.getTime());
int diffInYears = thatDay.get(Calendar.YEAR) - today.get(Calendar.YEAR);
int diffInDays = ((diffInYears*365) + thatDay.get(Calendar.DAY_OF_YEAR)) - today.get(Calendar.DAY_OF_YEAR);
diffInDays--; // Decrementing because I will be taking 1 day (which is 24 hours) to do below hours calculation
int diffInHours = thatDay.get(Calendar.HOUR_OF_DAY)+23 - today.get(Calendar.HOUR_OF_DAY); // Used 23 hours instead of 24 hours because I am using 1 hour (60 minutes) to do below calculation
int diffInMins = thatDay.get(Calendar.MINUTE)+60 - today.get(Calendar.MINUTE);
System.out.println(diffInDays + " days " + diffInHours + " hours " + diffInMins +" minutes remaining");
int SECONDS = 1000;
int MINUTE = SECONDS * 60 ;
int HOUR = MINUTE * 60;
int DAY = HOUR * 24;
I would start with diff and divide by DAY and then modula by DAY to get the
remainder for the next part.
repeat for HOUR, and MINUTE and SECOND
SimpleDateFormat: This will accomplish your goal quite easily.
Simply do the following..
SimpleDateFormat fmt = new SimpleDateFormat... (read the java docs)
fmt.format(your string)
No need to re-invent the wheel and make your program larger... This code already exists in Java.
EDIT: Since OP can't read..
S Millisecond Number 978

Convert simple time format to Special time format (hhmmt)

I'm trying to convert the time format (hh:mm:ss) to this Special Time Format (hhmmt)?
The Special Time Format (STF) is a 5 digit integer value with the format [hhmmt] where hh are the hours, mm are the minutes and t is the tenth of a minute.
For example, 04:41:05 would convert to 4411.
I'm not sure how to convert the seconds value (05) to a tenth of a minute (1).
Edit:
I've incorporated Adithya's suggestion below to convert seconds to a tenth of a minute, but I'm still stuck.
Here is my current code:
String[] timeInt = time.split(":");
String hours = timeInt[0];
String minutes = timeInt[1];
double seconds = Double.parseDouble(timeInt[2]);
int t = (int) Math.round(seconds/6);
if (t>=10) {
int min = Integer.parseInt(minutes);
// min+=1;
t = 0;
}
String stf="";
stf += hours;
stf += minutes;
stf += String.valueOf(t);
int stf2 = Integer.parseInt(stf);
return stf2;
I'm using a String to store the minutes value but it makes it difficult to increment it since it is a String and not a Integer. But when calculating the "t" (tenth of minute) I have to add 1 to minutes if it exceeds 10. If I were to use parseInt again it will exclude the 0 in front of minutes again.
How can I retain the leading zero and still increment the minutes?
Thanks.
I am guessing, its the value of seconds, compared to the tenth of a minute, which is 6 seconds. So formula for t would be
t= seconds/6 //rounded off to nearest integer
This makes sense as this value is always between 0 and 9, as seconds range from 0 and 59, so its always a single digit
For your example
t = 5/6 = 0.833 = rounded off to 1
Note the 6.0f in the division - this helps you avoid the INT truncation.
string FormatSpecialTime(string time)
{
if (time.Length != 8) throw YourException();
int HH, mm, SS, t;
if (!int.TryParse(time.Substring(0, 2), out HH)) HH = 0;
if (!int.TryParse(time.Substring(0, 2), out mm)) mm = 0;
if (!int.TryParse(time.Substring(0, 2), out SS)) SS = 0;
t = (int) Math.Round(SS / 6.0f);
if (t >= 10)
{
mm++;
t = 0;
}
if (mm >= 60)
{
HH += mm / 60;
mm = mm % 60;
}
return HH.ToString() + (mm > 10 ? mm.ToString() : #"0" + mm) + t;
}

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