Calculating the time difference with seconds - java

Here I have got the code part which counts the difference between two times(time1,time2).
How can I add seconds to it and convert 60sec to one minute?
I assume there is a simpler way to deal with it, but I am studying with book for beginners so I'd like to get the answer in the same way as the hours and minutes are calculated here.
hours=time2/100-time1/100;
mins=time2%100-time1%100;
hours=mins>0?hours:hours-1;
mins=mins>0?mins:mins+60;

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
long startTime = sdf.parse("10:00:00").getTime();
long endTIme = sdf.parse("11:00:00").getTime();
long duration = endTIme - startTime;
int seconds = (int) (duration / 1000) % 60;
int minutes = (int) ((duration / (1000 * 60)) % 60);
int hours = (int) ((duration / (1000 * 60 * 60)) % 24);

I am assume you have implemented the time as a number like 1234 is 12:34 In this case it is easier to parse each time and compare.
int mins1 = time1 / 100 * 60 + time1 % 100;
int mins2 = time2 / 100 * 60 + time2 % 100;
int diff = mins2 - mins1;
i want to do is input number 123456 which would be equal to 12:34:56
To handle seconds, you can do.
int secs1 = time1 / 10000 * 60 * 60 + time1 /100 % 100 * 60 + time1 % 100;
int secs2 = time2 / 10000 * 60 * 60 + time2 /100 % 100 * 60 + time2 % 100;
int diffInSec = secs1 - secs2;

Related

Error in my calculations for a y2k38 count down

Hey I need to make a program that counts down the days/ hours/ min/ sec until y2k38 i got the code but I have a logic error and am getting the wrong number for hours mins and secs. Heres my code:
public class Assignment1 {
public static void main(String[] args) {
long now = System.currentTimeMillis();
// The problem will occur at 2^31 seconds
long y2k38 = (long) Math.pow(2, 31)*1000;
// Assigning the time intervals values based on eachother
long diffsec = (y2k38-now)/1000;
long diffmin = diffsec/60;
long diffhours = diffmin/60;
long diffdays = diffhours/24;
// issuing a print statement to output the days,hours..etc until y2k38
System.out.printf(
"%d days\n"+
"%d hours\n"+
"%d minutes\n"+
"%d seconds\n",
(diffdays),(diffmin%60), (diffsec%3600),(diffsec%60));
}
}
Your calculations are all very strange, you can modify and print them as follows:
long diffsecs = (y2k38 - now) / 1000;
long diffmins = (diffsecs / 60) % 60;
long diffhours = (diffsecs / 60 / 60) % 24;
long diffdays = diffsecs / 60 / 60 / 24;
diffsecs = diffsecs % 60;
System.out.printf("%d days, %d hours, %d minutes, d seconds\n",
diffdays, diffhours, diffmins, diffsecs);
This gives you something like:
8126 days, 22 hours, 42 minutes, 21 seconds
which roughly matches what you need.
You are converting the difference into total days/hours/mins/secs. Instead, you want to start with finding days, and use the reminder to find hours, and so on.
long diff = y2k38 - now;
long diffdays = diff/(24*60*60*1000);
diff = diff%(24*60*60*1000);
long diffhours = diff/(60*60*1000);
diff = diff%(60*60*1000);
long diffmin = diff/(60*1000);
diff = diff%(60*1000);
long diffsec = diff/1000;
Also it's faster to compute the y2k38 value by
long y2k38 = ((long)(Integer.MAX_VALUE) + 1)*1000;

explanation about converting milliseconds to minutes

public String timeDifference(String startTime, String leavedTime) {
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1;
String dd =null;
try {
date1 = format.parse(startTime);
Date date2 = format.parse(leavedTime);
long difference = date2.getTime() - date1.getTime();
long diffMinutes = difference / (60 * 1000) % 60;
long diffHours = difference / (60 * 60 * 1000) % 24;
dd=diffHours + " : " + diffMinutes ;
} catch (ParseException ex) {
System.out.println(ex);
}
return dd;
}
I want to know about ,
1)long diffMinutes = difference / (60 * 1000) % 60;
2) long diffHours = difference / (60 * 60 * 1000) % 24
what is the purpose of using % 60 in code 1
what is the purpose of using % 24 in code 2
can anyone give me a clear explanation?
The % operator is the modulus operation. In this code, diffMinutes will be the number of minutes within the hour of the time difference, and diffHours will be the number of hours within the time difference.
Dividing by (60 * 1000) converts the original difference in milliseconds to units of minutes (divide by 1000 to get seconds, then by 60 to get minutes).
For example, if the time difference is 2 days 3 hours and 52 minutes, diffMinutes will be 52 and diffHours will be 3.
Without the modulus, the result changes from "the number of minutes within the hour" to "the total number of elapsed minutes". For example, 133 minutes elapsed (without the modulus) becomes "13 minutes within the hour" with the modulus.

TimeUtil package in java [duplicate]

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

Calculating time diffrence

I am trying to calculate time diffrence between dates:
public static void main(String args[])
{
String start = "2013-03-10 10:28:47.000000";
String end = "2013-04-07 09:54:08.054577";
CalculateDuration calc = new CalculateDuration();
calc.calculateDiffrenceInMinutes(start,end);
}
public int calculateDiffrenceInMinutes(String start_time, String end_time)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(start_time);
d2 = format.parse(end_time);
} catch (ParseException e) {
e.printStackTrace();
}
// Get msec from each, and subtract.
int diff = (int) d2.getTime() - (int)d1.getTime();
int diffSeconds = (int) (diff / 1000);
int diffMinutes = (int) (diff / (60 * 1000));
int diffHours = (int) (diff / (60 * 60 * 1000));
return diffMinutes;
}
For some reason i cant understand the example i show give a negetive output even though the end date is after the start date.
Any ideas?
Try changing
int diff = (int) d2.getTime() - (int)d1.getTime();
to
long diff = d2.getTime() - d1.getTime();
Explicit typecasting from long to int will cause precision loss and may result in a negative value on subtraction.
long a = 90000000000000L;
long b = 10000001000000L;
a>b
(int)a-(int)b => negative value
As others pointed out about precision loss, you can read the details in here.
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 60;
Java's date-time API has some design issues. Calendar is not thread safe. You may want to look at Joda-Time. This would make it as simple as-
Seconds.between(startDate, endDate);
Date#getTime() returns a long and that has a reason. Because quite a few milliseconds have passed since January 1, 1970, 00:00:00 GMT. An int can't hold that huge number (and overflows, which explains why you might get negative numbers (depending on the two dates)). So you should use long to do the calculations.
I would change your code like this:
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / ( 1000);
long diffMinutes = diff / ( 60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
Of course, you also need to change the return type of your calculateDiffrenceInMinutes method to long.
Note: In your example, you could also leave diffSeconds, diffMinutes and diffHours as int. But I wouldn't recommend that, as this would be a solution that fails if the dates are too far apart.

How to convert milliseconds to "hh:mm:ss" format?

I'm confused. After stumbling upon this thread, I tried to figure out how to format a countdown timer that had the format hh:mm:ss.
Here's my attempt -
//hh:mm:ss
String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.MINUTES.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
So, when I try a value like 3600000ms, I get 01:59:00, which is wrong since it should be 01:00:00. Obviously there's something wrong with my logic, but at the moment, I cannot see what it is!
Can anyone help?
Edit -
Fixed it. Here's the right way to format milliseconds to hh:mm:ss format -
//hh:mm:ss
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))));
The problem was this TimeUnit.MINUTES.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)). It should have been this TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)) instead.
You were really close:
String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), // The change is in this line
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
You were converting hours to millisseconds using minutes instead of hours.
BTW, I like your use of the TimeUnit API :)
Here's some test code:
public static void main(String[] args) throws ParseException {
long millis = 3600000;
String hms = 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)));
System.out.println(hms);
}
Output:
01:00:00
I realised that my code above can be greatly simplified by using a modulus division instead of subtraction:
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));
Still using the TimeUnit API for all magic values, and gives exactly the same output.
The generic method for this is fairly simple:
public static String convertSecondsToHMmSs(long seconds) {
long s = seconds % 60;
long m = (seconds / 60) % 60;
long h = (seconds / (60 * 60)) % 24;
return String.format("%d:%02d:%02d", h,m,s);
}
If you are using apache commons:
DurationFormatUtils.formatDuration(timeInMS, "HH:mm:ss,SSS");
I used this:
String.format("%1$tH:%1$tM:%1$tS.%1$tL", millis);
See description of class Formatter.
See runnable example using input of 2400 ms.
// New date object from millis
Date date = new Date(millis);
// formattter
SimpleDateFormat formatter= new SimpleDateFormat("HH:mm:ss.SSS");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
// Pass date object
String formatted = formatter.format(date );
You can also use new DateTime API
var formatted = DateTimeFormatter.ofPattern("HH:mm:ss.SSS")
.withZone(ZoneId.of("UTC"))
.format(Instant.ofEpochMilli(millis));
DateFormat df = new SimpleDateFormat("HH:mm:ss");
String formatted = df.format(aDateObject);
this worked for me, with kotlin
fun formatToDigitalClock(miliSeconds: Long): String {
val hours = TimeUnit.MILLISECONDS.toHours(miliSeconds).toInt() % 24
val minutes = TimeUnit.MILLISECONDS.toMinutes(miliSeconds).toInt() % 60
val seconds = TimeUnit.MILLISECONDS.toSeconds(miliSeconds).toInt() % 60
return when {
hours > 0 -> String.format("%d:%02d:%02d", hours, minutes, seconds)
minutes > 0 -> String.format("%02d:%02d", minutes, seconds)
seconds > 0 -> String.format("00:%02d", seconds)
else -> {
"00:00"
}
}
}
Test results for the 4 implementations
Having to do a lot of formatting for huge data, needed the best performance, so here are the (surprising) results:
for (int i = 0; i < 1000000; i++) {
FUNCTION_CALL
}
Durations:
combinationFormatter: 196 millis
formatDuration: 272 millis
apacheFormat: 754 millis
formatTimeUnit: 2216 millis
public static String apacheFormat(long millis) throws ParseException {
return DurationFormatUtils.formatDuration(millis, "HH:mm:ss");
}
public static String formatTimeUnit(long millis) throws ParseException {
String formatted = 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)));
return formatted;
}
public static String formatDuration(final long millis) {
long seconds = (millis / 1000) % 60;
long minutes = (millis / (1000 * 60)) % 60;
long hours = millis / (1000 * 60 * 60);
StringBuilder b = new StringBuilder();
b.append(hours == 0 ? "00" : hours < 10 ? String.valueOf("0" + hours) :
String.valueOf(hours));
b.append(":");
b.append(minutes == 0 ? "00" : minutes < 10 ? String.valueOf("0" + minutes) :
String.valueOf(minutes));
b.append(":");
b.append(seconds == 0 ? "00" : seconds < 10 ? String.valueOf("0" + seconds) :
String.valueOf(seconds));
return b.toString();
}
public static String combinationFormatter(final long millis) {
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis));
long hours = TimeUnit.MILLISECONDS.toHours(millis);
StringBuilder b = new StringBuilder();
b.append(hours == 0 ? "00" : hours < 10 ? String.valueOf("0" + hours) :
String.valueOf(hours));
b.append(":");
b.append(minutes == 0 ? "00" : minutes < 10 ? String.valueOf("0" + minutes) :
String.valueOf(minutes));
b.append(":");
b.append(seconds == 0 ? "00" : seconds < 10 ? String.valueOf("0" + seconds) :
String.valueOf(seconds));
return b.toString();
}
Java 9
Duration timeLeft = Duration.ofMillis(3600000);
String hhmmss = String.format("%02d:%02d:%02d",
timeLeft.toHours(), timeLeft.toMinutesPart(), timeLeft.toSecondsPart());
System.out.println(hhmmss);
This prints:
01:00:00
You are doing right in letting library methods do the conversions involved for you. java.time, the modern Java date and time API, or more precisely, its Duration class does it more elegantly and in a less error-prone way than TimeUnit.
The toMinutesPart and toSecondsPart methods I used were introduced in Java 9.
Java 6, 7 and 8
long hours = timeLeft.toHours();
timeLeft = timeLeft.minusHours(hours);
long minutes = timeLeft.toMinutes();
timeLeft = timeLeft.minusMinutes(minutes);
long seconds = timeLeft.toSeconds();
String hhmmss = String.format("%02d:%02d:%02d", hours, minutes, seconds);
System.out.println(hhmmss);
The output is the same as above.
Question: How can that work in Java 6 and 7?
In Java 8 and later and on newer Android devices (from API level 26, I’m told) java.time comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
The answer marked as correct has a little mistake,
String myTime = String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), // The change is in this line
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
for example this is an example of the value that i get:
417474:44:19
This is the solution to get the right format is:
String myTime = String.format("%02d:%02d:%02d",
//Hours
TimeUnit.MILLISECONDS.toHours(millis) -
TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(millis)),
//Minutes
TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
//Seconds
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
getting as a result a correct format:
18:44:19
other option to get the format hh:mm:ss is just :
Date myDate = new Date(timeinMillis);
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
String myTime = formatter.format(myDate);
public String millsToDateFormat(long mills) {
Date date = new Date(mills);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
String dateFormatted = formatter.format(date);
return dateFormatted; //note that it will give you the time in GMT+0
}
Going by Bohemian's answer we need need not use TimeUnit to find a known value.
Much more optimal code would be
String hms = String.format("%02d:%02d:%02d", millisLeft/(3600*1000),
millisLeft/(60*1000) % 60,
millisLeft/1000 % 60);
Hope it helps
String string = String.format("%02d:%02d:%02d.%03d",
TimeUnit.MILLISECONDS.toHours(millisecend), TimeUnit.MILLISECONDS.toMinutes(millisecend) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisecend)),
TimeUnit.MILLISECONDS.toSeconds(millisecend) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisecend)), millisecend - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millisecend)));
Format: 00:00:00.000
Example: 615605 Millisecend
00:10:15.605
The code below does the conversion in both way
23:59:58:999 to 86398999
and than
86398999 to 23:59:58:999
import java.util.concurrent.TimeUnit;
public class TimeUtility {
public static void main(String[] args) {
long currentDateTime = System.currentTimeMillis();
String strTest = "23:59:58:999";
System.out.println(strTest);
long l = strToMilli(strTest);
System.out.println(l);
l += 1;
String str = milliToString(l);
System.out.println(str);
}
/**
* convert a time string into the equivalent long milliseconds
*
* #param strTime string fomratted as HH:MM:SS:MSMS i.e. "23:59:59:999"
* #return long integer like 86399999
*/
public static long strToMilli(String strTime) {
long retVal = 0;
String hour = strTime.substring(0, 2);
String min = strTime.substring(3, 5);
String sec = strTime.substring(6, 8);
String milli = strTime.substring(9, 12);
int h = Integer.parseInt(hour);
int m = Integer.parseInt(min);
int s = Integer.parseInt(sec);
int ms = Integer.parseInt(milli);
String strDebug = String.format("%02d:%02d:%02d:%03d", h, m, s, ms);
//System.out.println(strDebug);
long lH = h * 60 * 60 * 1000;
long lM = m * 60 * 1000;
long lS = s * 1000;
retVal = lH + lM + lS + ms;
return retVal;
}
/**
* convert time in milliseconds to the corresponding string, in case of day
* rollover start from scratch 23:59:59:999 + 1 = 00:00:00:000
*
* #param millis the number of milliseconds corresponding to tim i.e.
* 34137999 that can be obtained as follows;
* <p>
* long lH = h * 60 * 60 * 1000; //hour to milli
* <p>
* long lM = m * 60 * 1000; // minute to milli
* <p>
* long lS = s * 1000; //seconds to milli
* <p>
* millis = lH + lM + lS + ms;
* #return a string formatted as HH:MM:SS:MSMS i.e. "23:59:59:999"
*/
private static String milliToString(long millis) {
long hrs = TimeUnit.MILLISECONDS.toHours(millis) % 24;
long min = TimeUnit.MILLISECONDS.toMinutes(millis) % 60;
long sec = TimeUnit.MILLISECONDS.toSeconds(millis) % 60;
//millis = millis - (hrs * 60 * 60 * 1000); //alternative way
//millis = millis - (min * 60 * 1000);
//millis = millis - (sec * 1000);
//long mls = millis ;
long mls = millis % 1000;
String toRet = String.format("%02d:%02d:%02d:%03d", hrs, min, sec, mls);
//System.out.println(toRet);
return toRet;
}
}
I tried as shown in the first answer. It works, but minus brought me into confusion. My answer by Groovy:
import static java.util.concurrent.TimeUnit.*
...
private static String formatElapsedTime(long millis) {
int hrs = MILLISECONDS.toHours(millis) % 24
int min = MILLISECONDS.toMinutes(millis) % 60
int sec = MILLISECONDS.toSeconds(millis) % 60
int mls = millis % 1000
sprintf( '%02d:%02d:%02d (%03d)', [hrs, min, sec, mls])
}
For Kotlin
val hours = String.format("%02d", TimeUnit.MILLISECONDS.toHours(milSecs))
val minutes = String.format("%02d",
TimeUnit.MILLISECONDS.toMinutes(milSecs) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milSecs)))
val seconds = String.format("%02d",
TimeUnit.MILLISECONDS.toSeconds(milSecs) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milSecs)))
where, milSecs is milliseconds
Well, you could try something like this, :
public String getElapsedTimeHoursMinutesSecondsString() {
long elapsedTime = getElapsedTime();
String format = String.format("%%0%dd", 2);
elapsedTime = elapsedTime / 1000;
String seconds = String.format(format, elapsedTime % 60);
String minutes = String.format(format, (elapsedTime % 3600) / 60);
String hours = String.format(format, elapsedTime / 3600);
String time = hours + ":" + minutes + ":" + seconds;
return time;
}
to convert milliseconds to a time value
In kotlin
private fun stringForTime(timeMs: Int): String {
val totalSeconds = timeMs / 1000
val seconds = totalSeconds % 60
val minutes = totalSeconds / 60 % 60
val hours = totalSeconds / 3600
return if (hours > 0) {
"%d:%02d:%02d".format(hours, minutes, seconds)
} else {
"%02d:%02d".format(minutes, seconds)
}
}
In Java
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = totalSeconds / 60 % 60;
int hours = totalSeconds / 3600;
return hours > 0 ? String.format(Locale.getDefault(),
"%d:%02d:%02d",
hours,
minutes,
seconds) :
String.format(Locale.getDefault(),
"%02d:%02d",
minutes,
seconds);
}
In Kotlin:
fun FUNCTION_NAME(milliSeconds: Long): String {
val s: Long = milliSeconds / 1000 % 60
val m: Long = milliSeconds / (1000*60) % 60
val h: Long = milliSeconds / (1000*60*60) % 24
return String.format("%02d:%02d:%02d", h, m, s)
}

Categories