explanation about converting milliseconds to minutes - java

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.

Related

Calculate the difference between two dates in hours:minutes:seconds?

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

Error in my calculations for a y2k38 count down

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

Time calculation with negative value results Java

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;

Calculating time diffrence

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

Calculating the time difference with seconds

Here I have got the code part which counts the difference between two times(time1,time2).
How can I add seconds to it and convert 60sec to one minute?
I assume there is a simpler way to deal with it, but I am studying with book for beginners so I'd like to get the answer in the same way as the hours and minutes are calculated here.
hours=time2/100-time1/100;
mins=time2%100-time1%100;
hours=mins>0?hours:hours-1;
mins=mins>0?mins:mins+60;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
long startTime = sdf.parse("10:00:00").getTime();
long endTIme = sdf.parse("11:00:00").getTime();
long duration = endTIme - startTime;
int seconds = (int) (duration / 1000) % 60;
int minutes = (int) ((duration / (1000 * 60)) % 60);
int hours = (int) ((duration / (1000 * 60 * 60)) % 24);
I am assume you have implemented the time as a number like 1234 is 12:34 In this case it is easier to parse each time and compare.
int mins1 = time1 / 100 * 60 + time1 % 100;
int mins2 = time2 / 100 * 60 + time2 % 100;
int diff = mins2 - mins1;
i want to do is input number 123456 which would be equal to 12:34:56
To handle seconds, you can do.
int secs1 = time1 / 10000 * 60 * 60 + time1 /100 % 100 * 60 + time1 % 100;
int secs2 = time2 / 10000 * 60 * 60 + time2 /100 % 100 * 60 + time2 % 100;
int diffInSec = secs1 - secs2;

Categories