Is it efficient to execute timer calculations in CountDownTimer -> onTick()? - java

I am displaying a visual countdown in a TextView, and I would like to know if there is a more efficient way of implementing the countdown logic. I feel like doing the calculation on each tick (even though the calculations are simple) might consume battery over time.
long now = Calendar.getInstance().getTimeInMillis();
Calendar midnight = new GregorianCalendar();
midnight.set(Calendar.HOUR_OF_DAY, 0);
midnight.set(Calendar.MINUTE, 0);
midnight.set(Calendar.SECOND, 0);
midnight.set(Calendar.MILLISECOND, 0);
midnight.add(Calendar.DAY_OF_MONTH, 1);
long deadline = midnight.getTimeInMillis();
long diff = deadline - now;
new CountDownTimer(diff, 1000) {
public void onTick(long millisUntilFinished) {
long days = TimeUnit.MILLISECONDS.toDays(millisUntilFinished);
long hours = TimeUnit.MILLISECONDS.toHours(millisUntilFinished) - (days * 24);
long minutes = TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - (days * 24 * 60) - (hours * 60);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - (days * 24 * 60 * 60) - (hours * 60 * 60) - (minutes * 60);
String fDays = String.format(Locale.FRANCE, "%d", days) + "J";
String fHours = String.format(Locale.FRANCE, "%d", hours) + "h";
String fMinutes = String.format(Locale.FRANCE, "%d", minutes) + "min";
String fSeconds = String.format(Locale.FRANCE, "%d", seconds) + "s";
fMinutes = (minutes < 10) ? "0" + fMinutes : fMinutes;
fSeconds = (seconds < 10) ? "0" + fSeconds : fSeconds;
String countDown = days > 0 ? fDays : "";
countDown += (!countDown.isEmpty() || hours > 0) ? fHours : null;
countDown += (!countDown.isEmpty() || minutes > 0) ? fMinutes : null;
countDown += (!countDown.isEmpty() || seconds > 0) ? fSeconds : null;
mTextView.setText(countDown);
}
public void onFinish() {
mTextView.setText("done!");
}
}.start();

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.

java difference between two dates

I need help. I have two dates.
private Date endDate;
private Date now;
public String getRemainingTime(endDate) {
now = new Date();
//logic
}
And also I have method whic should return difference between two dates in String formate, if difference more than 1 day - "1 day 15 min" for example;
if difference more than 1 hour but less than 1 day - "1 hour 13 min" for example;
and if difference less than 1 hour - "35 min 39sec", something like this...
Please help me, I'm not familiar with java.
Updated
1) This code will do the job (compiler will wrap constants):
public String getIntervalAsString(Date date1, Date date2) {
String format;
long dT = date2.getTime() - date1.getTime();
if (dT < 1000 * 60)
format = "s 'sec'";
else if (dT < 1000 * 60 * 60)
format = "m 'min' s 'sec'";
else if (dT < 1000 * 60 * 60 * 24)
format = "h 'hour(s)' m 'min'";
else if (dT < 1000 * 60 * 60 * 24 * 365)
format = "d 'day(s)' h 'hour(s)'";
else
format = "'more than a year'";
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.format(new Date(dT));
}
2) you may try different patterns here
if suggested comments link doesn't workout, then try this:
`
Date endDate;
Date now;
StringBuilder sb = new StringBuilder();
//timestamp difference in millis
Long diff = endaDate.getTime() - now.getTime();
//get the seconds
long seconds = diff / 1000;
//get the minutes
long minutes = diff / (1000 * 60);
//get the hours
long hrs = diff / (1000 * 60 * 60);
if (hrs > 0) {
sb.append(hrs + " hrs");
if (minutes % 60 > 0) {
sb.append(", " + minutes % 60 + " mins");
}
if (seconds % 60 > 0) {
sb.append(", " + seconds % 60 + " secs");
}
} else if (minutes % 60 > 0) {
sb.append(minutes % 60 + " mins");
if (seconds % 60 > 0) {
sb.append(", " + seconds % 60 + " secs");
}
} else if (seconds % 60 > 0) {
sb.append(seconds % 60 + " secs");
} else {
sb.append("00");
}
System.out.println(sb.toString());
`
private static final long MILLIS_PER_SECOND = 1000L;
private static final long MILLIS_PER_MINUTE = MILLIS_PER_SECOND * 60L;
private static final long MILLIS_PER_HOUR = MILLIS_PER_MINUTE * 60L;
private static final long MILLIS_PER_DAY = MILLIS_PER_HOUR * 24L;
public String getRemainingTime(Date endDate) {
long remain = endDate.getTime() - System.currentTimeMillis();
if (remain <= 0L) {
return "pass";
}
long days = remain / MILLIS_PER_DAY;
long hours = (remain % MILLIS_PER_DAY) / MILLIS_PER_HOUR;
long minutes = (remain % MILLIS_PER_HOUR) / MILLIS_PER_MINUTE;
long seconds = (remain % MILLIS_PER_MINUTE) / MILLIS_PER_SECOND;
StringBuilder sb = new StringBuilder();
if (days > 0L) {
sb.append(days).append(" day ");
}
if (hours > 0L || days > 0L) {
sb.append(hours).append(" hour ");
}
if (minutes > 0L || days > 0L || hours > 0L) {
sb.append(minutes).append(" min ");
}
if (seconds > 0L) {
sb.append(seconds).append(" sec");
}
return sb.toString();
}
The Joda-Time library might match your needs:
DateTime now
DateTime endDate;
Period p = new Period(now, endDate);
long hours = p.getHours();
long minutes = p.getMinutes();

How to Show time difference or reverse time in android

class revrsetime {
public static void main(String[] args) {
System.out.println(setLastSeenTime("26/08/2014 14:29:00"));
}
public static String setLastSeenTime(String time) {
long milliseconds = Math.abs(System.currentTimeMillis()
- converTimeStringINToMillis(time));
String lastSeen = "";
long seconds = (long) milliseconds / 1000;
if (seconds < 60)
lastSeen = String.valueOf(seconds) + "sec ago";
else if (seconds > 60 && seconds < 3600)
lastSeen = String.valueOf((int) seconds / 60) + " min ago";
else if (seconds > 3600 && seconds < 86400)
lastSeen = String.valueOf((int) seconds / 3600) + " hours ago";
else if (seconds > 86400 && seconds < 172800)
lastSeen = " Yesterday";
else if (seconds > 172800 && seconds < 2592000)
lastSeen = String.valueOf((int) (seconds / (24 * 3600)))
+ " days ago";
else if (seconds > 2592000)
lastSeen = String.valueOf((int) (seconds / (30 * 24 * 3600)))
+ " months ago";
return lastSeen;
}
private static long converTimeStringINToMillis(String time) {
long milliseconds = 0;
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
// 25/06/2014 8:41:26
Date date;
date = sdf.parse(time);
milliseconds = date.getTime();
} catch (ParseException e) {
// TODO Auto-generated catch block
milliseconds = 0;
e.printStackTrace();
}
return milliseconds;
}
}
This my code for display Lastseendate and time what I am doing this I have getting time from web service and system time make it differences. In some cases I am getting the correct Output but in others I am not.
The output when I set date and time : 26/08/2014 13:29:00 then it shows 3 hours ago when it should show 2 hours ago. When I set 26/08/2014 14:29:00 then it shows 4 hours ago.
I don't know where I'm making the mistake, please help.
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); remove this in Code it will Work fine.

How to find the duration of difference between two dates in java?

I have two objects of DateTime, which need to find the duration of their difference,
I have the following code but not sure how to continue it to get to the expected results as following:
Example:
11/03/14 09:30:58
11/03/14 09:33:43
elapsed time is 02 minutes and 45 seconds
-----------------------------------------------------
11/03/14 09:30:58
11/03/15 09:30:58
elapsed time is a day
-----------------------------------------------------
11/03/14 09:30:58
11/03/16 09:30:58
elapsed time is two days
-----------------------------------------------------
11/03/14 09:30:58
11/03/16 09:35:58
elapsed time is two days and 05 minutes
Code:
String dateStart = "11/03/14 09:29:58";
String dateStop = "11/03/14 09:33:43";
Custom date format
SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
} catch (ParseException e) {
e.printStackTrace();
}
// Get msec from each, and subtract.
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
System.out.println("Time in seconds: " + diffSeconds + " seconds.");
System.out.println("Time in minutes: " + diffMinutes + " minutes.");
System.out.println("Time in hours: " + diffHours + " hours.");
The date difference conversion could be handled in a better way using Java built-in class, TimeUnit. It provides utility methods to do that:
Date startDate = // Set start date
Date endDate = // Set end date
long duration = endDate.getTime() - startDate.getTime();
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);
try the following
{
Date dt2 = new DateAndTime().getCurrentDateTime();
long diff = dt2.getTime() - dt1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
int diffInDays = (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));
if (diffInDays > 1) {
System.err.println("Difference in number of days (2) : " + diffInDays);
return false;
} else if (diffHours > 24) {
System.err.println(">24");
return false;
} else if ((diffHours == 24) && (diffMinutes >= 1)) {
System.err.println("minutes");
return false;
}
return true;
}
Use Joda-Time library
DateTime startTime, endTime;
Period p = new Period(startTime, endTime);
long hours = p.getHours();
long minutes = p.getMinutes();
Joda Time has a concept of time Interval:
Interval interval = new Interval(oldTime, new Instant());
One more example
Date Difference
One more Link
or with Java-8 (which integrated Joda-Time concepts)
Instant start, end;//
Duration dur = Duration.between(start, stop);
long hours = dur.toHours();
long minutes = dur.toMinutes();
Here is how the problem can solved in Java 8 just like the answer by shamimz.
Source : http://docs.oracle.com/javase/tutorial/datetime/iso/period.html
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);
Period p = Period.between(birthday, today);
long p2 = ChronoUnit.DAYS.between(birthday, today);
System.out.println("You are " + p.getYears() + " years, " + p.getMonths() + " months, and " + p.getDays() + " days old. (" + p2 + " days total)");
The code produces output similar to the following:
You are 53 years, 4 months, and 29 days old. (19508 days total)
We have to use LocalDateTime http://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html to get hour,minute,second differences.
You can create a method like
public long getDaysBetweenDates(Date d1, Date d2){
return TimeUnit.MILLISECONDS.toDays(d1.getTime() - d2.getTime());
}
This method will return the number of days between the 2 days.
Date d2 = new Date();
Date d1 = new Date(1384831803875l);
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
int diffInDays = (int) diff / (1000 * 60 * 60 * 24);
System.out.println(diffInDays+" days");
System.out.println(diffHours+" Hour");
System.out.println(diffMinutes+" min");
System.out.println(diffSeconds+" sec");
As Michael Borgwardt writes in his answer here:
int diffInDays = (int)( (newerDate.getTime() - olderDate.getTime())
/ (1000 * 60 * 60 * 24) )
Note that this works with UTC dates, so the difference may be a day
off if you look at local dates. And getting it to work correctly with
local dates requires a completely different approach due to daylight
savings time.
It worked for me can try with this, hope it will be helpful . Let me know if any concern .
Date startDate = java.util.Calendar.getInstance().getTime(); //set your start time
Date endDate = java.util.Calendar.getInstance().getTime(); // set your end time
long duration = endDate.getTime() - startDate.getTime();
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);
Toast.makeText(MainActivity.this, "Diff"
+ duration + diffInDays + diffInHours + diffInMinutes + diffInSeconds, Toast.LENGTH_SHORT).show(); **// Toast message for android .**
System.out.println("Diff" + duration + diffInDays + diffInHours + diffInMinutes + diffInSeconds); **// Print console message for Java .**
In Java 8, you can make of DateTimeFormatter, Duration, and LocalDateTime. Here is an example:
final String dateStart = "11/03/14 09:29:58";
final String dateStop = "11/03/14 09:33:43";
final DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendValue(ChronoField.MONTH_OF_YEAR, 2)
.appendLiteral('/')
.appendValue(ChronoField.DAY_OF_MONTH, 2)
.appendLiteral('/')
.appendValueReduced(ChronoField.YEAR, 2, 2, 2000)
.appendLiteral(' ')
.appendValue(ChronoField.HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(ChronoField.MINUTE_OF_HOUR, 2)
.appendLiteral(':')
.appendValue(ChronoField.SECOND_OF_MINUTE, 2)
.toFormatter();
final LocalDateTime start = LocalDateTime.parse(dateStart, formatter);
final LocalDateTime stop = LocalDateTime.parse(dateStop, formatter);
final Duration between = Duration.between(start, stop);
System.out.println(start);
System.out.println(stop);
System.out.println(formatter.format(start));
System.out.println(formatter.format(stop));
System.out.println(between);
System.out.println(between.get(ChronoUnit.SECONDS));
This is the code:
String date1 = "07/15/2013";
String time1 = "11:00:01";
String date2 = "07/16/2013";
String time2 = "22:15:10";
String format = "MM/dd/yyyy HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date fromDate = sdf.parse(date1 + " " + time1);
Date toDate = sdf.parse(date2 + " " + time2);
long diff = toDate.getTime() - fromDate.getTime();
String dateFormat="duration: ";
int diffDays = (int) (diff / (24 * 60 * 60 * 1000));
if(diffDays>0){
dateFormat+=diffDays+" day ";
}
diff -= diffDays * (24 * 60 * 60 * 1000);
int diffhours = (int) (diff / (60 * 60 * 1000));
if(diffhours>0){
dateFormat+=diffhours+" hour ";
}
diff -= diffhours * (60 * 60 * 1000);
int diffmin = (int) (diff / (60 * 1000));
if(diffmin>0){
dateFormat+=diffmin+" min ";
}
diff -= diffmin * (60 * 1000);
int diffsec = (int) (diff / (1000));
if(diffsec>0){
dateFormat+=diffsec+" sec";
}
System.out.println(dateFormat);
and the out is:
duration: 1 day 11 hour 15 min 9 sec
I solved the similar problem using a simple method recently.
public static void main(String[] args) throws IOException, ParseException {
TimeZone utc = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(utc);
Date until = calendar.getTime();
calendar.add(Calendar.DAY_OF_MONTH, -7);
Date since = calendar.getTime();
long durationInSeconds = TimeUnit.MILLISECONDS.toSeconds(until.getTime() - since.getTime());
long SECONDS_IN_A_MINUTE = 60;
long MINUTES_IN_AN_HOUR = 60;
long HOURS_IN_A_DAY = 24;
long DAYS_IN_A_MONTH = 30;
long MONTHS_IN_A_YEAR = 12;
long sec = (durationInSeconds >= SECONDS_IN_A_MINUTE) ? durationInSeconds % SECONDS_IN_A_MINUTE : durationInSeconds;
long min = (durationInSeconds /= SECONDS_IN_A_MINUTE) >= MINUTES_IN_AN_HOUR ? durationInSeconds%MINUTES_IN_AN_HOUR : durationInSeconds;
long hrs = (durationInSeconds /= MINUTES_IN_AN_HOUR) >= HOURS_IN_A_DAY ? durationInSeconds % HOURS_IN_A_DAY : durationInSeconds;
long days = (durationInSeconds /= HOURS_IN_A_DAY) >= DAYS_IN_A_MONTH ? durationInSeconds % DAYS_IN_A_MONTH : durationInSeconds;
long months = (durationInSeconds /=DAYS_IN_A_MONTH) >= MONTHS_IN_A_YEAR ? durationInSeconds % MONTHS_IN_A_YEAR : durationInSeconds;
long years = (durationInSeconds /= MONTHS_IN_A_YEAR);
String duration = getDuration(sec,min,hrs,days,months,years);
System.out.println(duration);
}
private static String getDuration(long secs, long mins, long hrs, long days, long months, long years) {
StringBuffer sb = new StringBuffer();
String EMPTY_STRING = "";
sb.append(years > 0 ? years + (years > 1 ? " years " : " year "): EMPTY_STRING);
sb.append(months > 0 ? months + (months > 1 ? " months " : " month "): EMPTY_STRING);
sb.append(days > 0 ? days + (days > 1 ? " days " : " day "): EMPTY_STRING);
sb.append(hrs > 0 ? hrs + (hrs > 1 ? " hours " : " hour "): EMPTY_STRING);
sb.append(mins > 0 ? mins + (mins > 1 ? " mins " : " min "): EMPTY_STRING);
sb.append(secs > 0 ? secs + (secs > 1 ? " secs " : " secs "): EMPTY_STRING);
sb.append("ago");
return sb.toString();
}
And as expected it prints: 7 days ago.
with reference to shamim's answer update here is a method that does the task without using any third party library. Just copy the method and use
public static String getDurationTimeStamp(String date) {
String timeDifference = "";
//date formatter as per the coder need
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//parse the string date-ti
// me to Date object
Date startDate = null;
try {
startDate = sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
//end date will be the current system time to calculate the lapse time difference
//if needed, coder can add end date to whatever date
Date endDate = new Date();
System.out.println(startDate);
System.out.println(endDate);
//get the time difference in milliseconds
long duration = endDate.getTime() - startDate.getTime();
//now we calculate the differences in different time units
//this long value will be the total time difference in each unit
//i.e; total difference in seconds, total difference in minutes etc...
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);
//now we create the time stamps depending on the value of each unit that we get
//as we do not have the unit in years,
//we will see if the days difference is more that 365 days, as 365 days = 1 year
if (diffInDays > 365) {
//we get the year in integer not in float
//ex- 791/365 = 2.167 in float but it will be 2 years in int
int year = (int) (diffInDays / 365);
timeDifference = year + " years ago";
System.out.println(year + " years ago");
}
//if days are not enough to create year then get the days
else if (diffInDays > 1) {
timeDifference = diffInDays + " days ago";
System.out.println(diffInDays + " days ago");
}
//if days value<1 then get the hours
else if (diffInHours > 1) {
timeDifference = diffInHours + " hours ago";
System.out.println(diffInHours + " hours ago");
}
//if hours value<1 then get the minutes
else if (diffInMinutes > 1) {
timeDifference = diffInMinutes + " minutes ago";
System.out.println(diffInMinutes + " minutes ago");
}
//if minutes value<1 then get the seconds
else if (diffInSeconds > 1) {
timeDifference = diffInSeconds + " seconds ago";
System.out.println(diffInSeconds + " seconds ago");
}
return timeDifference;
// that's all. Happy Coding :)
}
java.time.Duration
I still didn’t feel any of the answers was quite up to date and to the point. So here is the modern answer using Duration from java.time, the modern Java date and time API (the answers by MayurB and mkobit mention the same class, but none of them correctly converts to days, hours, minutes and minutes as asked).
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yy/MM/dd HH:mm:ss");
String dateStart = "11/03/14 09:29:58";
String dateStop = "11/03/14 09:33:43";
ZoneId zone = ZoneId.systemDefault();
ZonedDateTime startDateTime = LocalDateTime.parse(dateStart, formatter).atZone(zone);
ZonedDateTime endDateTime = LocalDateTime.parse(dateStop, formatter).atZone(zone);
Duration diff = Duration.between(startDateTime, endDateTime);
if (diff.isZero()) {
System.out.println("0 minutes");
} else {
long days = diff.toDays();
if (days != 0) {
System.out.print("" + days + " days ");
diff = diff.minusDays(days);
}
long hours = diff.toHours();
if (hours != 0) {
System.out.print("" + hours + " hours ");
diff = diff.minusHours(hours);
}
long minutes = diff.toMinutes();
if (minutes != 0) {
System.out.print("" + minutes + " minutes ");
diff = diff.minusMinutes(minutes);
}
long seconds = diff.getSeconds();
if (seconds != 0) {
System.out.print("" + seconds + " seconds ");
}
System.out.println();
}
Output from this example snippet is:
3 minutes 45 seconds
Note that Duration always counts a day as 24 hours. If you want to treat time anomalies like summer time transistions differently, solutions inlcude (1) use ChronoUnit.DAYS (2) Use Period (3) Use LocalDateTimeinstead ofZonedDateTime` (may be considered a hack).
The code above works with Java 8 and with ThreeTen Backport, that backport of java.time to Java 6 and 7. From Java 9 it may be possible to write it a bit more nicely using the methods toHoursPart, toMinutesPart and toSecondsPart added there.
I will elaborate the explanations further one of the days when I get time, maybe not until next week.
This is a program I wrote, which gets the number of days between 2 dates(no time here).
import java.util.Scanner;
public class HelloWorld {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.print("Enter starting date separated by dots: ");
String inp1 = s.nextLine();
System.out.print("Enter ending date separated by dots: ");
String inp2 = s.nextLine();
int[] nodim = {
0,
31,
28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
};
String[] inpArr1 = split(inp1);
String[] inpArr2 = split(inp2);
int d1 = Integer.parseInt(inpArr1[0]);
int m1 = Integer.parseInt(inpArr1[1]);
int y1 = Integer.parseInt(inpArr1[2]);
int d2 = Integer.parseInt(inpArr2[0]);
int m2 = Integer.parseInt(inpArr2[1]);
int y2 = Integer.parseInt(inpArr2[2]);
if (y1 % 4 == 0) nodim[2] = 29;
int diff = m1 == m2 && y1 == y2 ? d2 - (d1 - 1) : (nodim[m1] - (d1 - 1));
int mm1 = m1 + 1, mm2 = m2 - 1, yy1 = y1, yy2 = y2;
for (; yy1 <= yy2; yy1++, mm1 = 1) {
mm2 = yy1 == yy2 ? (m2 - 1) : 12;
if (yy1 % 4 == 0) nodim[2] = 29;
else nodim[2] = 28;
if (mm2 == 0) {
mm2 = 12;
yy2 = yy2 - 1;
}
for (; mm1 <= mm2 && yy1 <= yy2; mm1++) diff = diff + nodim[mm1];
}
System.out.print("No. of days from " + inp1 + " to " + inp2 + " is " + diff);
}
public static String[] split(String s) {
String[] retval = {
"",
"",
""
};
s = s + ".";
s = s + " ";
for (int i = 0; i <= 2; i++) {
retval[i] = s.substring(0, s.indexOf("."));
s = s.substring((s.indexOf(".") + 1), s.length());
}
return retval;
}
}
http://pastebin.com/HRsjTtUf
You can get the difference between two DateTime using this
DateTime startDate = DateTime.now();
DateTime endDate = DateTime.now();
Days daysBetween = Days.daysBetween(startDate, endDate);
System.out.println(daysBetween.toStandardSeconds());
The below code will give the difference between two DateTime (Will work in Java 8 and above)
private long countDaysBetween(LocalDateTime startDate, LocalDateTime enddate)
{
if(startDate == null || enddate == null)
{
throw new IllegalArgumentException("No such a date");
}
long daysBetween = ChronoUnit.DAYS.between(startDate, enddate);
return daysBetween;
}
If anyone wants a string with all of them together, this function can be used.
String getTimeDifference(long duration) {
StringBuilder timeRemaining = new StringBuilder();
long days = TimeUnit.MILLISECONDS.toDays(duration);
if (days >= 1) {
timeRemaining.append(days).append((days == 1) ? " day " : " days ");
}
duration -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(duration);
if (hours >= 1) {
timeRemaining.append(hours).append((hours == 1) ? " hour " : " hours ");
}
duration -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration);
if (minutes >= 1) {
timeRemaining.append(minutes).append((hours == 1) ? " minute " : " minutes ");
}
return timeRemaining.toString().trim();
}
// calculating the difference b/w startDate and endDate
String startDate = "01-01-2016";
String endDate = simpleDateFormat.format(currentDate);
date1 = simpleDateFormat.parse(startDate);
date2 = simpleDateFormat.parse(endDate);
long getDiff = date2.getTime() - date1.getTime();
// using TimeUnit class from java.util.concurrent package
long getDaysDiff = TimeUnit.MILLISECONDS.toDays(getDiff);
How to calculate difference between two dates in Java

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