I want to calculate the difference between a start time and an end time. In HH:mm format.
I receive a negative value when, for example, the start time is 22.00 and the end time is 1.00 the next day.
How do I let the program know the end time is on the next day?
My script:
public void setBeginTijd()
{
String dateStart = "22:00";
String dateEnd = "1:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date d1 = null;
Date d2 = null;
try
{
d1 = format.parse(dateStart);
d2 = format.parse(dateEnd);
long diff = d2.getTime() - d1.getTime();
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
System.out.println(diffMinutes);
System.out.println(diffHours);
}
catch (Exception e)
{
e.printStackTrace();
}
}
If you can assume that, when the time is negative, the second time must be on the next day, then you can simply say
if (diff < 0)
{
diff = (24 * 60 * 60 * 1000) + diff;
}
EDIT to elaborate this, also in response to the comments: Of course this is a very simplistic solution. It can not handle the case where the second date is two days later. It does not handle DST switches. It does not handle the time zone change on December 31st, 1927 in Shanghai. It is no replacement for a properly modelled date with all its caveats. It is a best-effort approach to derive what can (probably) be derived from the given information.
Try this
SimpleDateFormat formatNextDay = new SimpleDateFormat("dd:HH:mm");
boolean isNextDay=false;
try {
if (d1.after(d2)) {
isNextDay=true;
d1 = formatNextDay.parse("1:" + dateStart);
d2 = formatNextDay.parse("2:" + dateEnd);
}
As already mentioned by some people, it is important to also know day, month and year of each event to calculate periods for events that are not on the same day.
I modified your method the way I think it could help you:
public void setBeginTijd()
{
String dateStart = "22.08.2014 22:00";
String dateEnd = "25.08.2014 01:00";
SimpleDateFormat fullFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
Date d1 = null;
Date d2 = null;
try
{
d1 = fullFormat.parse(dateStart);
d2 = fullFormat.parse(dateEnd);
long diff = d2.getTime() - d1.getTime();
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Delta minutes: " + diffMinutes);
System.out.println("Delta hours: " + diffHours);
System.out.println("Delta days: " + diffDays);
}
catch (Exception e)
{
e.printStackTrace();
}
}
You should include day, month and year in date.
This are dates in Java after ran program:
d1 = Thu Jan 01 22:00:00 CET 1970
d2 = Thu Jan 01 01:00:00 CET 1970
Here is the correct math for time difference in hours & minutes. Stripping of the decimal fraction is happening automatically when you operate on int/long values.
long diff = d2.getTime() - d1.getTime();
long diffHours = diff / 1000 / 60 / 60;
long diffMinutes = diff / 1000 / 60 - diffHours * 60;
Related
How can I calculate the difference between two dates and show it in the format hours:minutes:seconds?
Example:
StartTime : 2016-12-20T04:30
EndTime : 2016-12-22T05:00
The output should be "48hours 30minutes 0 seconds".
This is what I've tried:
Long diff = (endDate.get time() -startDate.gettime())/1000;
Log.d("App","difference in hour is"+diff/1000/60/60);
Mins = diff/1000/60;
Seconds = diff/1000;
Using this code I'm getting hours as a correct value. But the minute and seconds values are not getting their proper values.
Try this function:-
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate){
//milliseconds
long different = endDate.getTime() - startDate.getTime();
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
//long elapsedDays = different / daysInMilli;
//different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
System.out.printf(
"%d hours, %d minutes, %d seconds%n",
elapsedHours, elapsedMinutes, elapsedSeconds);
}
Try
1. Add following methods first, then use parseDate.
Date startDate = parseDate("2016-12-20T04:30");
Date endDate = parseDate("2016-12-22T05:00");
2. Calculate difference b/w these two
long differenceInMillis = endDate.getTime() - startDate.getTime();
3. Use formatElapsedTime method to formatted difference
String formattedText = formatElapsedTime(differenceInMillis/1000); //divide by 1000 to get seconds from milliseconds
//Result will be 48hours 30minutes 0 seconds
public static Date parseDate (String strDate) {
DateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm");
Date date1 = null;
try {
date1 = dateFormat.parse (strDate);
}
catch (ParseException e) {
e.printStackTrace ();
}
return date1;
}
public static String formatElapsedTime (long seconds) {
long hours = TimeUnit.SECONDS.toHours(seconds);
seconds -= TimeUnit.HOURS.toSeconds (hours);
long minutes = TimeUnit.SECONDS.toMinutes (seconds);
seconds -= TimeUnit.MINUTES.toSeconds (minutes);
return String.format ("%dhr:%dmin:%dsec", hours, minutes, seconds);
}
import java.util.Calendar;
public class DateDifferenceExample {
public static void main(String[] args) {
// Creates two calendars instances
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
// Set the date for both of the calendar instance
cal1.set(2006, Calendar.DECEMBER, 30);
cal2.set(2007, Calendar.MAY, 3);
// Get the represented date in milliseconds
long millis1 = cal1.getTimeInMillis();
long millis2 = cal2.getTimeInMillis();
// Calculate difference in milliseconds
long diff = millis2 - millis1;
// Calculate difference in seconds
long diffSeconds = diff / 1000;
// Calculate difference in minutes
long diffMinutes = diff / (60 * 1000);
// Calculate difference in hours
long diffHours = diff / (60 * 60 * 1000);
// Calculate difference in days
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("In milliseconds: " + diff + " milliseconds.");
System.out.println("In seconds: " + diffSeconds + " seconds.");
System.out.println("In minutes: " + diffMinutes + " minutes.");
System.out.println("In hours: " + diffHours + " hours.");
System.out.println("In days: " + diffDays + " days.");
}
}
New answer to an old question using a newer API: java.time
You can write a method that actually accepts the datetimes as Strings along with a time zone and then calculates the difference by means of a class designed for such purpose: java.time.Duration
Here's a code example:
public static String getDifference(String firstDt, String secondDt, String zone) {
// create the zone for the calculation just to respect daylight saving time
ZoneId zoneId = ZoneId.of(zone);
// then parse the datetimes passed and add the time zone
ZonedDateTime firstZdt = ZonedDateTime.of(
LocalDateTime.parse(firstDt), zoneId
);
ZonedDateTime secondZdt = ZonedDateTime.of(
LocalDateTime.parse(secondDt), zoneId
);
// calculate the duration between the two datetimes
Duration duration;
/*
* the JavaDocs of Duration tell us the following:
*
* "The result of this method can be a negative period
* if the end is before the start.".
*
* So we need to make sure the older datetime will be
* the "start" in the method "between(start, end)"
*/
if (firstZdt.isAfter(secondZdt)) {
duration = Duration.between(secondZdt, firstZdt);
} else {
duration = Duration.between(firstZdt, secondZdt);
}
// store the amount of full hours the duration has
long hoursBetween;
hoursBetween = duration.toHours();
// calculate the minutes left from the full duration in minutes
long minutesBetween;
minutesBetween = duration.toMinutes() - (hoursBetween * 60);
// calculate the seconds left from the full duration in seconds
long secondsBetween;
secondsBetween = duration.getSeconds() - (duration.toMinutes() * 60);
// build the result String, take care of possibly missing leading zeros
StringBuilder resultBuilder = new StringBuilder();
resultBuilder.append(hoursBetween).append(" hours ");
if (minutesBetween < 10 && minutesBetween > 0)
resultBuilder.append("0");
resultBuilder.append(minutesBetween).append(" minutes ");
if (secondsBetween < 10 && secondsBetween > 0)
resultBuilder.append("0");
resultBuilder.append(secondsBetween).append(" seconds");
return resultBuilder.toString();
}
If you use it in a main...
public static void main(String[] args) {
String timeDiff = getDifference("2016-12-20T04:30", "2016-12-22T05:00", "UTC");
System.out.println(timeDiff);
}
... you will get the following output:
48 hours 30 minutes 0 seconds
The code above is the one to be used in Java 8, later on, Duration got the methods toHoursPart(), toMinutesPart() and toSecondsPart() which actually do the necessary calculation internally.
The code that would change (tried with Java 11):
// store the amount of full hours the duration has
long hoursBetween;
hoursBetween = duration.toHoursPart();
// calculate the minutes left from the full duration in minutes
long minutesBetween;
minutesBetween = duration.toMinutesPart();
// calculate the seconds left from the full duration in seconds
long secondsBetween;
secondsBetween = duration.toSecondsPart();
public String timeDifference(String startTime, String leavedTime) {
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1;
String dd =null;
try {
date1 = format.parse(startTime);
Date date2 = format.parse(leavedTime);
long difference = date2.getTime() - date1.getTime();
long diffMinutes = difference / (60 * 1000) % 60;
long diffHours = difference / (60 * 60 * 1000) % 24;
dd=diffHours + " : " + diffMinutes ;
} catch (ParseException ex) {
System.out.println(ex);
}
return dd;
}
I want to know about ,
1)long diffMinutes = difference / (60 * 1000) % 60;
2) long diffHours = difference / (60 * 60 * 1000) % 24
what is the purpose of using % 60 in code 1
what is the purpose of using % 24 in code 2
can anyone give me a clear explanation?
The % operator is the modulus operation. In this code, diffMinutes will be the number of minutes within the hour of the time difference, and diffHours will be the number of hours within the time difference.
Dividing by (60 * 1000) converts the original difference in milliseconds to units of minutes (divide by 1000 to get seconds, then by 60 to get minutes).
For example, if the time difference is 2 days 3 hours and 52 minutes, diffMinutes will be 52 and diffHours will be 3.
Without the modulus, the result changes from "the number of minutes within the hour" to "the total number of elapsed minutes". For example, 133 minutes elapsed (without the modulus) becomes "13 minutes within the hour" with the modulus.
I trying convert unix milliseconds to gmt date, I need only hours and minutes, but results are incorrect according to online converters.
What I need
Here is my code:
public static void main(String[] args) {
long time = 1438050023;
// TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time / 1000);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss dd MM yyyy");
simpleDateFormat.setTimeZone(calendar.getTimeZone());
System.out.println(simpleDateFormat.format(calendar.getTime()));
}
Result:
03:23:58 01 01 1970
Change calendar.setTimeInMillis(time / 1000) to calendar.setTimeInMillis(time * 1000)
The number of milliseconds is 1000 times the number of seconds; not 1/1000 the number.
public static String ConvertMillistoDatetime(long millis) {
long second = (millis / 1000) % 60;
long minute = (millis / (1000 * 60)) % 60;
long hour = (millis / (1000 * 60 * 60)) % 24;
return String.format("%02d:%02d:%02d", hour, minute, second);
}
Try this you can keep seconds optional here
I have two times in String format. 9:00 AM and 10:00 AM. I want to subtract them. the difference must be 1 hour. I tried the following code to do that but i am not getting the desired results:
String time1 = "9:00 AM";
String time2 = "10:00 AM";
SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
Date d1 = formatter.parse(time1);
Date d2 = formatter.parse(time2);
long timeDiff = d2.getTime() - d1.getTime();
Date diff = new Date(timeDiff);
System.out.println(formatter.format(diff));
How can i do that ?
Try something like:
long timeDiff = d2.getTime() - d1.getTime();
System.out.println((timeDiff / 3600000) + " hour/s " + (timeDiff % 3600000) / 60000 + " minutes");
Output
1 hour/s 5 minutes
Use Joda time! See this question
DateTimeFormatter formatter = DateTimeFormat.forPattern("H:mm a");
DateTime time1 = formatter.parseDateTime("9:00 AM");
DateTime time2 = formatter.parseDateTime("10:00 AM");
Duration duration = new Duration(time1, time2);
System.out.printf("%s hour(s), %s minute(s)%n", duration.getStandardHours(), duration.getStandardMinutes());
Your approach seems to be correct.
Only thing you should not do is, changing timeDiff to new Date.
Rather, change it to get time in minutes and hours as follows
Ex : -
long diffMinutes = timeDiff / (60 * 1000) % 60;
long diffHours = timeDiff / (60 * 60 * 1000) % 24;
System.out.println(diffHours+" hours "+ diffMinutes +" minutes");
here is the complete code You can refer to if you want more proper display of time difference,
import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.*;
/* Name of the class has to be "Main" only if the class is public. */
class TimeDiffTester
{
public static String show(long value, String showAs) {
if(value == 0) {
return "";
} else {
return Math.abs(value) +" "+showAs+" ";
}
}
public static void getDifferenceInTime(String time1, String time2) throws java.lang.Exception {
SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
Date d1 = formatter.parse(time1);
Date d2 = formatter.parse(time2);
long timeDiff = d2.getTime() - d1.getTime();
long diffDays = timeDiff / (24 * 60 * 60 * 1000);
long diffHours = timeDiff / (60 * 60 * 1000) % 24;
long diffMinutes = timeDiff / (60 * 1000) % 60;
long diffSeconds = timeDiff / 1000 % 60;
String difference = show(diffDays, "days") + show(diffHours, "hours") + show(diffMinutes, "minutes") + show(diffSeconds, "seconds");
if(diffDays < 0 || diffHours < 0 || diffMinutes < 0 || diffSeconds < 0) {
System.out.println("-"+difference);
} else {
System.out.println("+"+difference);
}
}
public static void main (String[] args) throws java.lang.Exception
{
String time1 = "4:30 PM";
String time2 = "5:00 PM";
getDifferenceInTime(time1,time2);
}
}
Here is best example given.
1000 milliseconds = 1 second
60 seconds = 1 minute
60 minutes = 1 hour
24 hours = 1 day
public static void main(String[] args) {
String dateStart = "01/14/2012 09:29:58";
String dateStop = "01/15/2012 10:31:48";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
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.");
} catch (Exception e) {
e.printStackTrace();
}
}
Please find reference link for this example
http://www.mkyong.com/java/how-to-calculate-date-time-difference-in-java/
I am trying to calculate time diffrence between dates:
public static void main(String args[])
{
String start = "2013-03-10 10:28:47.000000";
String end = "2013-04-07 09:54:08.054577";
CalculateDuration calc = new CalculateDuration();
calc.calculateDiffrenceInMinutes(start,end);
}
public int calculateDiffrenceInMinutes(String start_time, String end_time)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(start_time);
d2 = format.parse(end_time);
} catch (ParseException e) {
e.printStackTrace();
}
// Get msec from each, and subtract.
int diff = (int) d2.getTime() - (int)d1.getTime();
int diffSeconds = (int) (diff / 1000);
int diffMinutes = (int) (diff / (60 * 1000));
int diffHours = (int) (diff / (60 * 60 * 1000));
return diffMinutes;
}
For some reason i cant understand the example i show give a negetive output even though the end date is after the start date.
Any ideas?
Try changing
int diff = (int) d2.getTime() - (int)d1.getTime();
to
long diff = d2.getTime() - d1.getTime();
Explicit typecasting from long to int will cause precision loss and may result in a negative value on subtraction.
long a = 90000000000000L;
long b = 10000001000000L;
a>b
(int)a-(int)b => negative value
As others pointed out about precision loss, you can read the details in here.
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 60;
Java's date-time API has some design issues. Calendar is not thread safe. You may want to look at Joda-Time. This would make it as simple as-
Seconds.between(startDate, endDate);
Date#getTime() returns a long and that has a reason. Because quite a few milliseconds have passed since January 1, 1970, 00:00:00 GMT. An int can't hold that huge number (and overflows, which explains why you might get negative numbers (depending on the two dates)). So you should use long to do the calculations.
I would change your code like this:
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / ( 1000);
long diffMinutes = diff / ( 60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
Of course, you also need to change the return type of your calculateDiffrenceInMinutes method to long.
Note: In your example, you could also leave diffSeconds, diffMinutes and diffHours as int. But I wouldn't recommend that, as this would be a solution that fails if the dates are too far apart.