Related
This question already has answers here:
How to convert Milliseconds to "X mins, x seconds" in Java?
(29 answers)
Closed 6 years ago.
I want to calculate difference between 2 dates in hours/minutes/seconds.
I have a slight problem with my code here it is :
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;
long diffMinutes = diff / (60 * 1000);
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.");
This should produce :
Time in seconds: 45 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.
However I get this result :
Time in seconds: 225 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.
Can anyone see what I'm doing wrong here ?
I would prefer to use suggested java.util.concurrent.TimeUnit class.
long diff = d2.getTime() - d1.getTime();//as given
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
try
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
NOTE: this assumes that diff is non-negative.
If you are able to use external libraries I would recommend you to use Joda-Time, noting that:
Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).
Example for between calculation:
Seconds.between(startDate, endDate);
Days.between(startDate, endDate);
Try this for a friendly representation of time differences (in milliseconds):
String friendlyTimeDiff(long timeDifferenceMilliseconds) {
long diffSeconds = timeDifferenceMilliseconds / 1000;
long diffMinutes = timeDifferenceMilliseconds / (60 * 1000);
long diffHours = timeDifferenceMilliseconds / (60 * 60 * 1000);
long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
long diffWeeks = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 7);
long diffMonths = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 30.41666666));
long diffYears = timeDifferenceMilliseconds / ((long)60 * 60 * 1000 * 24 * 365);
if (diffSeconds < 1) {
return "less than a second";
} else if (diffMinutes < 1) {
return diffSeconds + " seconds";
} else if (diffHours < 1) {
return diffMinutes + " minutes";
} else if (diffDays < 1) {
return diffHours + " hours";
} else if (diffWeeks < 1) {
return diffDays + " days";
} else if (diffMonths < 1) {
return diffWeeks + " weeks";
} else if (diffYears < 1) {
return diffMonths + " months";
} else {
return diffYears + " years";
}
}
Since Java 5, you can use java.util.concurrent.TimeUnit to avoid the use of Magic Numbers like 1000 and 60 in your code.
By the way, you should take care to leap seconds in your computation: the last minute of a year may have an additional leap second so it indeed lasts 61 seconds instead of expected 60 seconds. The ISO specification even plan for possibly 61 seconds. You can find detail in java.util.Date javadoc.
Here is a suggestion, using TimeUnit, to obtain each time part and format them.
private static String formatDuration(long duration) {
long hours = TimeUnit.MILLISECONDS.toHours(duration);
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration) % 60;
long seconds = TimeUnit.MILLISECONDS.toSeconds(duration) % 60;
long milliseconds = duration % 1000;
return String.format("%02d:%02d:%02d,%03d", hours, minutes, seconds, milliseconds);
}
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss,SSS");
Date startTime = sdf.parse("01:00:22,427");
Date now = sdf.parse("02:06:38,355");
long duration = now.getTime() - startTime.getTime();
System.out.println(formatDuration(duration));
The result is: 01:06:15,928
This is more of a maths problem than a java problem basically.
The result you receive is correct. This because 225 seconds is 3 minutes (when doing an integral division). What you want is the this:
divide by 1000 to get the number of seconds -> rest is milliseconds
divide that by 60 to get number of minutes -> rest are seconds
divide that by 60 to get number of hours -> rest are minutes
or in java:
int millis = diff % 1000;
diff/=1000;
int seconds = diff % 60;
diff/=60;
int minutes = diff % 60;
diff/=60;
hours = diff;
I know this is an old question, but I ended up doing something slightly different from the accepted answer. People talk about the TimeUnit class, but there were no answers using this in the way OP wanted it.
So here's another solution, should someone come by missing it ;-)
public class DateTesting {
public static void main(String[] args) {
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 days = TimeUnit.MILLISECONDS.toDays(diff);
long remainingHoursInMillis = diff - TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(remainingHoursInMillis);
long remainingMinutesInMillis = remainingHoursInMillis - TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(remainingMinutesInMillis);
long remainingSecondsInMillis = remainingMinutesInMillis - TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(remainingSecondsInMillis);
System.out.println("Days: " + days + ", hours: " + hours + ", minutes: " + minutes + ", seconds: " + seconds);
}
}
Although just calculating the difference yourself can be done, it's not very meaningful to do it like that and I think TimeUnit is a highly overlooked class.
Create a Date object using the diffence between your times as a constructor,
then use Calendar methods to get values ..
Date diff = new Date(d2.getTime() - d1.getTime());
Calendar calendar = Calendar.getInstance();
calendar.setTime(diff);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
difference-between-two-dates-in-java
Extracted the code from the link
public class TimeDiff {
/**
* (For testing purposes)
*
*/
public static void main(String[] args) {
Date d1 = new Date();
try { Thread.sleep(750); } catch(InterruptedException e) { /* ignore */ }
Date d0 = new Date(System.currentTimeMillis() - (1000*60*60*24*3)); // About 3 days ago
long[] diff = TimeDiff.getTimeDifference(d0, d1);
System.out.printf("Time difference is %d day(s), %d hour(s), %d minute(s), %d second(s) and %d millisecond(s)\n",
diff[0], diff[1], diff[2], diff[3], diff[4]);
System.out.printf("Just the number of days = %d\n",
TimeDiff.getTimeDifference(d0, d1, TimeDiff.TimeField.DAY));
}
/**
* Calculate the absolute difference between two Date without
* regard for time offsets
*
* #param d1 Date one
* #param d2 Date two
* #param field The field we're interested in out of
* day, hour, minute, second, millisecond
*
* #return The value of the required field
*/
public static long getTimeDifference(Date d1, Date d2, TimeField field) {
return TimeDiff.getTimeDifference(d1, d2)[field.ordinal()];
}
/**
* Calculate the absolute difference between two Date without
* regard for time offsets
*
* #param d1 Date one
* #param d2 Date two
* #return The fields day, hour, minute, second and millisecond
*/
public static long[] getTimeDifference(Date d1, Date d2) {
long[] result = new long[5];
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTime(d1);
long t1 = cal.getTimeInMillis();
cal.setTime(d2);
long diff = Math.abs(cal.getTimeInMillis() - t1);
final int ONE_DAY = 1000 * 60 * 60 * 24;
final int ONE_HOUR = ONE_DAY / 24;
final int ONE_MINUTE = ONE_HOUR / 60;
final int ONE_SECOND = ONE_MINUTE / 60;
long d = diff / ONE_DAY;
diff %= ONE_DAY;
long h = diff / ONE_HOUR;
diff %= ONE_HOUR;
long m = diff / ONE_MINUTE;
diff %= ONE_MINUTE;
long s = diff / ONE_SECOND;
long ms = diff % ONE_SECOND;
result[0] = d;
result[1] = h;
result[2] = m;
result[3] = s;
result[4] = ms;
return result;
}
public static void printDiffs(long[] diffs) {
System.out.printf("Days: %3d\n", diffs[0]);
System.out.printf("Hours: %3d\n", diffs[1]);
System.out.printf("Minutes: %3d\n", diffs[2]);
System.out.printf("Seconds: %3d\n", diffs[3]);
System.out.printf("Milliseconds: %3d\n", diffs[4]);
}
public static enum TimeField {DAY,
HOUR,
MINUTE,
SECOND,
MILLISECOND;
}
}
// d1, d2 are dates
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
Joda-Time
Joda-Time 2.3 library offers already-debugged code for this chore.
Joad-Time includes three classes to represent a span of time: Period, Interval, and Duration. Period tracks a span as a number of months, days, hours, etc. (not tied to the timeline).
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// Specify a time zone rather than rely on default.
// Necessary to handle Daylight Saving Time (DST) and other anomalies.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "yy/MM/dd HH:mm:ss" ).withZone( timeZone );
DateTime dateTimeStart = formatter.parseDateTime( "11/03/14 09:29:58" );
DateTime dateTimeStop = formatter.parseDateTime( "11/03/14 09:33:43" );
Period period = new Period( dateTimeStart, dateTimeStop );
PeriodFormatter periodFormatter = PeriodFormat.getDefault();
String output = periodFormatter.print( period );
System.out.println( "output: " + output );
When run…
output: 3 minutes and 45 seconds
Here is my code.
import java.util.Date;
// to calculate difference between two days
public class DateDifference {
// to calculate difference between two dates in milliseconds
public long getDateDiffInMsec(Date da, Date db) {
long diffMSec = 0;
diffMSec = db.getTime() - da.getTime();
return diffMSec;
}
// to convert Milliseconds into DD HH:MM:SS format.
public String getDateFromMsec(long diffMSec) {
int left = 0;
int ss = 0;
int mm = 0;
int hh = 0;
int dd = 0;
left = (int) (diffMSec / 1000);
ss = left % 60;
left = (int) left / 60;
if (left > 0) {
mm = left % 60;
left = (int) left / 60;
if (left > 0) {
hh = left % 24;
left = (int) left / 24;
if (left > 0) {
dd = left;
}
}
}
String diff = Integer.toString(dd) + " " + Integer.toString(hh) + ":"
+ Integer.toString(mm) + ":" + Integer.toString(ss);
return diff;
}
}
long diffSeconds = (diff / 1000)%60;
try this and let me know if it works correctly...
Well, I'll try yet another code sample:
/**
* Calculates the number of FULL days between to dates
* #param startDate must be before endDate
* #param endDate must be after startDate
* #return number of day between startDate and endDate
*/
public static int daysBetween(Calendar startDate, Calendar endDate) {
long start = startDate.getTimeInMillis();
long end = endDate.getTimeInMillis();
// It's only approximation due to several bugs (#see java.util.Date) and different precision in Calendar chosen
// by user (ex. day is time-quantum).
int presumedDays = (int) TimeUnit.MILLISECONDS.toDays(end - start);
startDate.add(Calendar.DAY_OF_MONTH, presumedDays);
// if we still didn't reach endDate try it with the step of one day
if (startDate.before(endDate)) {
startDate.add(Calendar.DAY_OF_MONTH, 1);
++presumedDays;
}
// if we crossed endDate then we must go back, because the boundary day haven't completed yet
if (startDate.after(endDate)) {
--presumedDays;
}
return presumedDays;
}
Date startTime = new Date();
//...
//... lengthy jobs
//...
Date endTime = new Date();
long diff = endTime.getTime() - startTime.getTime();
String hrDateText = DurationFormatUtils.formatDuration(diff, "d 'day(s)' H 'hour(s)' m 'minute(s)' s 'second(s)' ");
System.out.println("Duration : " + hrDateText);
You can use Apache Commons Duration Format Utils. It formats like SimpleDateFormatter
Output:
0 days(s) 0 hour(s) 0 minute(s) 1 second(s)
As said before - think this is a good answer
/**
* #param d2 the later date
* #param d1 the earlier date
* #param timeUnit - Example Calendar.HOUR_OF_DAY
* #return
*/
public static int getTimeDifference(Date d2,Date d1, int timeUnit) {
Date diff = new Date(d2.getTime() - d1.getTime());
Calendar calendar = Calendar.getInstance();
calendar.setTime(diff);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
if(timeUnit==Calendar.HOUR_OF_DAY)
return hours;
if(timeUnit==Calendar.MINUTE)
return minutes;
return seconds;
}
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();
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
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";
}
}
}
This question already has answers here:
How to convert Milliseconds to "X mins, x seconds" in Java?
(29 answers)
Closed 6 years ago.
I want to calculate difference between 2 dates in hours/minutes/seconds.
I have a slight problem with my code here it is :
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;
long diffMinutes = diff / (60 * 1000);
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.");
This should produce :
Time in seconds: 45 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.
However I get this result :
Time in seconds: 225 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.
Can anyone see what I'm doing wrong here ?
I would prefer to use suggested java.util.concurrent.TimeUnit class.
long diff = d2.getTime() - d1.getTime();//as given
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
try
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
NOTE: this assumes that diff is non-negative.
If you are able to use external libraries I would recommend you to use Joda-Time, noting that:
Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).
Example for between calculation:
Seconds.between(startDate, endDate);
Days.between(startDate, endDate);
Try this for a friendly representation of time differences (in milliseconds):
String friendlyTimeDiff(long timeDifferenceMilliseconds) {
long diffSeconds = timeDifferenceMilliseconds / 1000;
long diffMinutes = timeDifferenceMilliseconds / (60 * 1000);
long diffHours = timeDifferenceMilliseconds / (60 * 60 * 1000);
long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
long diffWeeks = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 7);
long diffMonths = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 30.41666666));
long diffYears = timeDifferenceMilliseconds / ((long)60 * 60 * 1000 * 24 * 365);
if (diffSeconds < 1) {
return "less than a second";
} else if (diffMinutes < 1) {
return diffSeconds + " seconds";
} else if (diffHours < 1) {
return diffMinutes + " minutes";
} else if (diffDays < 1) {
return diffHours + " hours";
} else if (diffWeeks < 1) {
return diffDays + " days";
} else if (diffMonths < 1) {
return diffWeeks + " weeks";
} else if (diffYears < 1) {
return diffMonths + " months";
} else {
return diffYears + " years";
}
}
Since Java 5, you can use java.util.concurrent.TimeUnit to avoid the use of Magic Numbers like 1000 and 60 in your code.
By the way, you should take care to leap seconds in your computation: the last minute of a year may have an additional leap second so it indeed lasts 61 seconds instead of expected 60 seconds. The ISO specification even plan for possibly 61 seconds. You can find detail in java.util.Date javadoc.
Here is a suggestion, using TimeUnit, to obtain each time part and format them.
private static String formatDuration(long duration) {
long hours = TimeUnit.MILLISECONDS.toHours(duration);
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration) % 60;
long seconds = TimeUnit.MILLISECONDS.toSeconds(duration) % 60;
long milliseconds = duration % 1000;
return String.format("%02d:%02d:%02d,%03d", hours, minutes, seconds, milliseconds);
}
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss,SSS");
Date startTime = sdf.parse("01:00:22,427");
Date now = sdf.parse("02:06:38,355");
long duration = now.getTime() - startTime.getTime();
System.out.println(formatDuration(duration));
The result is: 01:06:15,928
This is more of a maths problem than a java problem basically.
The result you receive is correct. This because 225 seconds is 3 minutes (when doing an integral division). What you want is the this:
divide by 1000 to get the number of seconds -> rest is milliseconds
divide that by 60 to get number of minutes -> rest are seconds
divide that by 60 to get number of hours -> rest are minutes
or in java:
int millis = diff % 1000;
diff/=1000;
int seconds = diff % 60;
diff/=60;
int minutes = diff % 60;
diff/=60;
hours = diff;
I know this is an old question, but I ended up doing something slightly different from the accepted answer. People talk about the TimeUnit class, but there were no answers using this in the way OP wanted it.
So here's another solution, should someone come by missing it ;-)
public class DateTesting {
public static void main(String[] args) {
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 days = TimeUnit.MILLISECONDS.toDays(diff);
long remainingHoursInMillis = diff - TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(remainingHoursInMillis);
long remainingMinutesInMillis = remainingHoursInMillis - TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(remainingMinutesInMillis);
long remainingSecondsInMillis = remainingMinutesInMillis - TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(remainingSecondsInMillis);
System.out.println("Days: " + days + ", hours: " + hours + ", minutes: " + minutes + ", seconds: " + seconds);
}
}
Although just calculating the difference yourself can be done, it's not very meaningful to do it like that and I think TimeUnit is a highly overlooked class.
Create a Date object using the diffence between your times as a constructor,
then use Calendar methods to get values ..
Date diff = new Date(d2.getTime() - d1.getTime());
Calendar calendar = Calendar.getInstance();
calendar.setTime(diff);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
difference-between-two-dates-in-java
Extracted the code from the link
public class TimeDiff {
/**
* (For testing purposes)
*
*/
public static void main(String[] args) {
Date d1 = new Date();
try { Thread.sleep(750); } catch(InterruptedException e) { /* ignore */ }
Date d0 = new Date(System.currentTimeMillis() - (1000*60*60*24*3)); // About 3 days ago
long[] diff = TimeDiff.getTimeDifference(d0, d1);
System.out.printf("Time difference is %d day(s), %d hour(s), %d minute(s), %d second(s) and %d millisecond(s)\n",
diff[0], diff[1], diff[2], diff[3], diff[4]);
System.out.printf("Just the number of days = %d\n",
TimeDiff.getTimeDifference(d0, d1, TimeDiff.TimeField.DAY));
}
/**
* Calculate the absolute difference between two Date without
* regard for time offsets
*
* #param d1 Date one
* #param d2 Date two
* #param field The field we're interested in out of
* day, hour, minute, second, millisecond
*
* #return The value of the required field
*/
public static long getTimeDifference(Date d1, Date d2, TimeField field) {
return TimeDiff.getTimeDifference(d1, d2)[field.ordinal()];
}
/**
* Calculate the absolute difference between two Date without
* regard for time offsets
*
* #param d1 Date one
* #param d2 Date two
* #return The fields day, hour, minute, second and millisecond
*/
public static long[] getTimeDifference(Date d1, Date d2) {
long[] result = new long[5];
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTime(d1);
long t1 = cal.getTimeInMillis();
cal.setTime(d2);
long diff = Math.abs(cal.getTimeInMillis() - t1);
final int ONE_DAY = 1000 * 60 * 60 * 24;
final int ONE_HOUR = ONE_DAY / 24;
final int ONE_MINUTE = ONE_HOUR / 60;
final int ONE_SECOND = ONE_MINUTE / 60;
long d = diff / ONE_DAY;
diff %= ONE_DAY;
long h = diff / ONE_HOUR;
diff %= ONE_HOUR;
long m = diff / ONE_MINUTE;
diff %= ONE_MINUTE;
long s = diff / ONE_SECOND;
long ms = diff % ONE_SECOND;
result[0] = d;
result[1] = h;
result[2] = m;
result[3] = s;
result[4] = ms;
return result;
}
public static void printDiffs(long[] diffs) {
System.out.printf("Days: %3d\n", diffs[0]);
System.out.printf("Hours: %3d\n", diffs[1]);
System.out.printf("Minutes: %3d\n", diffs[2]);
System.out.printf("Seconds: %3d\n", diffs[3]);
System.out.printf("Milliseconds: %3d\n", diffs[4]);
}
public static enum TimeField {DAY,
HOUR,
MINUTE,
SECOND,
MILLISECOND;
}
}
// d1, d2 are dates
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
Joda-Time
Joda-Time 2.3 library offers already-debugged code for this chore.
Joad-Time includes three classes to represent a span of time: Period, Interval, and Duration. Period tracks a span as a number of months, days, hours, etc. (not tied to the timeline).
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// Specify a time zone rather than rely on default.
// Necessary to handle Daylight Saving Time (DST) and other anomalies.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "yy/MM/dd HH:mm:ss" ).withZone( timeZone );
DateTime dateTimeStart = formatter.parseDateTime( "11/03/14 09:29:58" );
DateTime dateTimeStop = formatter.parseDateTime( "11/03/14 09:33:43" );
Period period = new Period( dateTimeStart, dateTimeStop );
PeriodFormatter periodFormatter = PeriodFormat.getDefault();
String output = periodFormatter.print( period );
System.out.println( "output: " + output );
When run…
output: 3 minutes and 45 seconds
Here is my code.
import java.util.Date;
// to calculate difference between two days
public class DateDifference {
// to calculate difference between two dates in milliseconds
public long getDateDiffInMsec(Date da, Date db) {
long diffMSec = 0;
diffMSec = db.getTime() - da.getTime();
return diffMSec;
}
// to convert Milliseconds into DD HH:MM:SS format.
public String getDateFromMsec(long diffMSec) {
int left = 0;
int ss = 0;
int mm = 0;
int hh = 0;
int dd = 0;
left = (int) (diffMSec / 1000);
ss = left % 60;
left = (int) left / 60;
if (left > 0) {
mm = left % 60;
left = (int) left / 60;
if (left > 0) {
hh = left % 24;
left = (int) left / 24;
if (left > 0) {
dd = left;
}
}
}
String diff = Integer.toString(dd) + " " + Integer.toString(hh) + ":"
+ Integer.toString(mm) + ":" + Integer.toString(ss);
return diff;
}
}
long diffSeconds = (diff / 1000)%60;
try this and let me know if it works correctly...
Well, I'll try yet another code sample:
/**
* Calculates the number of FULL days between to dates
* #param startDate must be before endDate
* #param endDate must be after startDate
* #return number of day between startDate and endDate
*/
public static int daysBetween(Calendar startDate, Calendar endDate) {
long start = startDate.getTimeInMillis();
long end = endDate.getTimeInMillis();
// It's only approximation due to several bugs (#see java.util.Date) and different precision in Calendar chosen
// by user (ex. day is time-quantum).
int presumedDays = (int) TimeUnit.MILLISECONDS.toDays(end - start);
startDate.add(Calendar.DAY_OF_MONTH, presumedDays);
// if we still didn't reach endDate try it with the step of one day
if (startDate.before(endDate)) {
startDate.add(Calendar.DAY_OF_MONTH, 1);
++presumedDays;
}
// if we crossed endDate then we must go back, because the boundary day haven't completed yet
if (startDate.after(endDate)) {
--presumedDays;
}
return presumedDays;
}
Date startTime = new Date();
//...
//... lengthy jobs
//...
Date endTime = new Date();
long diff = endTime.getTime() - startTime.getTime();
String hrDateText = DurationFormatUtils.formatDuration(diff, "d 'day(s)' H 'hour(s)' m 'minute(s)' s 'second(s)' ");
System.out.println("Duration : " + hrDateText);
You can use Apache Commons Duration Format Utils. It formats like SimpleDateFormatter
Output:
0 days(s) 0 hour(s) 0 minute(s) 1 second(s)
As said before - think this is a good answer
/**
* #param d2 the later date
* #param d1 the earlier date
* #param timeUnit - Example Calendar.HOUR_OF_DAY
* #return
*/
public static int getTimeDifference(Date d2,Date d1, int timeUnit) {
Date diff = new Date(d2.getTime() - d1.getTime());
Calendar calendar = Calendar.getInstance();
calendar.setTime(diff);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
if(timeUnit==Calendar.HOUR_OF_DAY)
return hours;
if(timeUnit==Calendar.MINUTE)
return minutes;
return seconds;
}