Getting wrong time after calculating difference between two Dates - java

I want to calculate the difference between a certain date and the current time.
int month = 9;
int day = 17;
int year = 2013;
Calendar date = new GregorianCalendar(year, month, day);
int miliseconds= (int) (System.currentTimeMillis() - calendar.getTimeInMillis());
System.out.println(msToString(second));
String msToString(int ms) {
return (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")).format(new Date(ms));
}
the output is
13091-13091/? D/GTA: 1970-01-08 15:00:20.287
I want to get the amount of days, hours,minutes and seconds remaining.
What do I wrong?

you could try something like the following method
import java.util.Calendar;
import java.util.GregorianCalendar;
public class TimeToGoCalculator {
/**
* #param args
*/
public static void main(String[] args) {
int month = 8;
int day = 19;
int year = 2013;
Calendar calendar = new GregorianCalendar(year, month, day);
int timeToGo = (int) (calendar.getTimeInMillis() - System.currentTimeMillis())/1000;
System.out.println(secondsToString(timeToGo));
}
private static String secondsToString(int seconds) {
int days = seconds / 24 / 3600;
int hours = (seconds - (days * 24 * 3600 )) / 3600;
int minutes = (seconds - (days * 24 * 3600 + hours * 3600)) / 60;
seconds = (seconds - (days * 24 * 3600 + hours * 3600 + minutes * 60));
return "The remaining time is "+days+" days, "+hours+" hours, "+minutes+
" minutes, and "+seconds+" seconds.";
}
}
That should give you the output you're looking for.
Notice that, when creating the GregorianCalendar object, the month is 0-indexed, so September would be = 8.

Use Joda Time library
Period class can help.
int month = 9;
int day = 17;
int year = 2013;
int hour= 0;
int minute =0;
int second =0;
int millisecond = 0;
DateTime dt1 = new DateTime(); //now
DateTime dt2 = new DateTime(year, month, day, hour, minute, second, millisecond);
//assuming dt1 is before dt2:
Period period = new Period(dt1, dt2, PeriodType.dayTime());
/*
periodType.dayTime()):
Gets a type that defines all standard fields from days downwards.
days
hours
minutes
seconds
milliseconds
*/
PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
.printZeroAlways()
.minimumPrintedDigits(2)
.appendDays().appendSuffix("days ")
.appendHours().appendSuffix("hours ")
.appendMinutes().appendSuffix("minutes ")
.appendSeconds().appendSuffix("seconds ");
.toFormatter();
System.out.println(periodFormatter.print(period));

Are you able to use external libraries? Then Joda Time can help you, especially the Period class.
It has a constructor for two time instants and gives you the difference between the time instants in years/months/days/hours/seconds/milliseconds.

Your second variable holds an amount of milliseconds between the two dates, not a new date. You need to do some calculation using these milliseconds to get an amount of days, for instance.
You could do something like this:
int minutes = second/1000/60; // millis to seconds, seconds to minutes
to get an amount of minutes, then convert to hours, and so on.

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

Java finding difference between times

i have some problem while finding difference between times, if i try to find difference in todays time (say t1 = "08:00:00" and t2 = "10:00:00" then it is giving correct output,)but when i try to find the difference like t1 = "20:00:00"(which is todays time) and t2 ="08:00:00"(which is next day morning),i want the output as 12 hours but i a getting wrong outputs. kindly help me.
String t1 = "20:00:00";
String t2 = "12:00:00";
String t3 = "24:00:00";
SimpleDateFormat sDf = new SimpleDateFormat("HH:mm:ss");
Date d1 = sDf.parse(t1);
Date d2 = sDf.parse(t2);
Date d3 = sDf.parse(t3);
long s1,s2,s3,s4,dif1,dif2,dif3,minutes,hrs;
dif1 = d2.getTime() - d1.getTime();
s1 = dif1/1000;
System.out.println("s1 "+s1);
if(s1<0){
dif2 = d3.getTime() - d1.getTime();
s2 = dif2/1000;
System.out.println("s2 "+s2);
dif3 = d2.getTime();
s3 = dif3/1000;
System.out.println("s3 "+s3);
s4 = s2+s3;
minutes = s4 / 60;
s4 = s4 % 60;
hrs = minutes / 60;
minutes = minutes % 60;
System.out.println("time difference is : "+hrs+": "+minutes+" :"+s4);
}else{
minutes = s1 / 60;
s1 = s1 % 60;
hrs = minutes / 60;
minutes = minutes % 60;
System.out.println("time difference is : "+hrs+": "+minutes+" :"+s1);
}
Any date/time manipulation/calculation should be done though the use of well defined and tested APIs like Java 8's Time API or Joda Time
Java 8
public class TestTime {
public static void main(String[] args) {
// Because of the ability for the time to roll over to the next
// day, we need the date component to make sense of it, for example
// 24:00 is actually 00:00 of the next day ... joy
LocalDateTime t1 = LocalTime.of(20, 00).atDate(LocalDate.now());
LocalDateTime t2 = LocalTime.of(12, 00).atDate(LocalDate.now());
LocalDateTime t3 = LocalTime.MIDNIGHT.atDate(LocalDate.now()).plusDays(1);
if (t1.isAfter(t2)) {
System.out.println("Before");
Duration duration = Duration.between(t2, t3);
System.out.println(format(duration));
} else {
System.out.println("After");
Duration duration = Duration.between(t2, t1);
System.out.println(format(duration));
}
}
public static String format(Duration duration) {
long hours = duration.toHours();
duration = duration.minusHours(hours);
return String.format("%02d hours %02d minutes", hours, duration.toMinutes());
}
}
Which outputs
12 hours 00 minutes
The question I can't seem to answer in your code is why you did this s4 = s2+s3;, basically adding 12:00 to 24:00
See some options here
such as :
LocalDate today = LocalDate.now()
LocalDate yeasterday = today.minusDays(1);
Duration oneDay = Duration.between(today, yesterday);
Duration.between(today.atTime(0, 0), yesterday.atTime(0, 0)).toDays() // another option
String time1 = "08:00:00";
String time2 = "17:00:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
Not using Java 8 or Joda-Time, and ensuring that local time zone DST is not involved.
public static void printDiff(String time1, String time2) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
int seconds = (int)(df.parse(time2).getTime() - df.parse(time1).getTime()) / 1000;
if (seconds < 0)
seconds += 24 * 60 * 60;
int minutes = seconds / 60;
int hours = minutes / 60;
seconds %= 60;
minutes %= 60;
System.out.printf("There are %d hours %d minutes %d seconds from %s to %s%n",
hours, minutes, seconds, time1, time2);
}
Test
public static void main(String[] args) throws Exception {
printDiff("08:00:00", "10:00:00");
printDiff("20:00:00", "08:00:00");
printDiff("15:47:22", "11:12:38");
printDiff("08:00:00", "07:59:59");
printDiff("08:00:00", "08:00:00");
}
Output
There are 2 hours 0 minutes 0 seconds from 08:00:00 to 10:00:00
There are 12 hours 0 minutes 0 seconds from 20:00:00 to 08:00:00
There are 19 hours 25 minutes 16 seconds from 15:47:22 to 11:12:38
There are 23 hours 59 minutes 59 seconds from 08:00:00 to 07:59:59
There are 0 hours 0 minutes 0 seconds from 08:00:00 to 08:00:00

system Time is showing but with the difference of 1 hour

time is not showing perfectly, I am trying to show my system timings.
Also I am not able to set these
int minut = calendar.getTime().getMinutes();
int hours = calendar.getTime().getHours();
int sec = calendar.getTime().getSeconds();
It gave error:
The method getSeconds() from the type Date is depreciated.
The method getHours() from the type Date is depreciated.
The method getMinutes() from the type Date is depreciated.
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
int hours = cal.getTime();
int minut = cal.getTime();
hours = hours * 30 + minut / 2;
minut = minut * 6;
int sec = cal.getTime();
minut = minut +sec/10;
sec = sec * 6;
hr.setRotate(hours);
minute.setRotate(minut);
second.setRotate(sec);
Scene sc = new Scene(pane);
ps.setScene(sc);
It give me the time for example if my system time is 10:25 it shows 09:25
Your code makes not much sense to me but get keep in mind that Calender.getTimeInMillis() or Date.getTime() return the time in UTC - regardless the timezone you set on the calendar.
Please try below code, it will give you correct time:
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
System.out.println(hour + ":" + minute + ":" + second + ":" + millis);

How to get GMT date from Unix epoch time milliseconds?

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

Add two String Times in java [duplicate]

This question already has answers here:
Sum two dates in Java
(9 answers)
Closed 8 years ago.
I have two String times
1:30:00
1:35:00
Is there a simple way to add these two times and get a new time which should be something
3:05:00?
I want to do this at client side , so if i can avoid any date liabraries
String time1="0:01:30";
String time2="0:01:35";
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date1 = timeFormat.parse(time1);
Date date2 = timeFormat.parse(time2);
long sum = date1.getTime() + date2.getTime();
String date3 = timeFormat.format(new Date(sum));
System.out.println("The sum is "+date3);
Ouput : The sum is 00:03:05
Keep in mind that you can convert int values for hours/minutes/seconds to a single int like this:
int totalSeconds = ((hours * 60) + minutes) * 60 + seconds;
And convert back:
int hours = totalSeconds / 3600; // Be sure to use integer arithmetic
int minutes = ((totalSeconds) / 60) % 60;
int seconds = totalSeconds % 60;
Or you can do arithmetic piecemeal as follows:
int totalHours = hours1 + hours2;
int totalMinutes = minutes1 + minutes2;
int totalSeconds = seconds1 + seconds2;
if (totalSeconds >= 60) {
totalMinutes ++;
totalSeconds = totalSeconds % 60;
}
if (totalMinutes >= 60) {
totalHours ++;
totalMinutes = totalMinutes % 60;
}
Use SimpleDateFormat to parse the Strings then you can add the hours minutes and seconds
something like
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
d1 = df.parse("1:30:00");
d2 = df.parse("1:35:00");
Long sumtime= d1.getTime()+d2.getTime();
you can see this here as well it looks like possible duplicate of #####
or if you want to use Calender API, then you can also do it using Calender API, then u can do something like
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
Calendar cTotal = Calendar.getInstance();
cTotal.add(c1.get(Calendar.YEAR), c2.get(Calendar.YEAR));
cTotal.add(c1.get(Calendar.MONTH) + 1)), c2.get(Calendar.MONTH) + 1)); // Months are zero-based!
cTotal.add(c1.get(Calendar.DATE), c2.get(Calendar.DATE));
Just sum them as you sum numbers in 1st-2nd grades, going backwards through them.
Also make sure you move over digits to higher register when needed (i.e. not
always when reaching 10 but when reaching 24 or 60 for hours/minutes).
So I suggest you code this algorithm yourself.

Categories