Calculate the difference. between two points, given that we have two different lines for time and date

I have temporary data divided into two lines - one line for the date and one for the time.
I want to calculate diff. such two times in Java.
eg

  • Time 1: 02/26/2011 and 11:00 AM
  • time 2: "02/27/2011" and "12:15 AM"

The difference will be 13 hours 15 minutes.

+6
java date time
source share
6 answers
String str_date1 = "26/02/2011"; String str_time1 = "11:00 AM"; String str_date2 = "27/02/2011"; String str_time2 = "12:15 AM" ; DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm a"); Date date1 = formatter.parse(str_date1 + " " + str_time1); Date date2 = formatter.parse(str_date2 + " " + str_time2); // Get msec from each, and subtract. long diff = date2.getTime() - date1.getTime(); System.out.println("Difference In Days: " + (diff / (1000 * 60 * 60 * 24))); 

Obs: This is true only as an approximation. See Losing time on the way to the garden .)

+10
source share
 try { String date1 = "26/02/2011"; String time1 = "11:00 AM"; String date2 = "27/02/2011"; String time2 = "12:15 AM"; String format = "dd/MM/yyyy hh:mm a"; SimpleDateFormat sdf = new SimpleDateFormat(format); Date dateObj1 = sdf.parse(date1 + " " + time1); Date dateObj2 = sdf.parse(date2 + " " + time2); System.out.println(dateObj1); System.out.println(dateObj2); long diff = dateObj2.getTime() - dateObj1.getTime(); double diffInHours = diff / ((double) 1000 * 60 * 60); System.out.println(diffInHours); System.out.println("Hours " + (int)diffInHours); System.out.println("Minutes " + (diffInHours - (int)diffInHours)*60 ); } catch (ParseException e) { e.printStackTrace(); } 

Exit

 Sat Feb 26 11:00:00 EST 2011 Sun Feb 27 00:15:00 EST 2011 13.25 Hours 13 Minutes 15.0 
+7
source share

Take a look at DateFormat , you can use it to parse your strings using the parsing method (String source), and you can easily manipulate the Dates object to get what you want.

 DateFormat df = DateFormat.getInstance(); Date date1 = df.parse(string1); Date date2 = df.parse(string2); long difference = date1.getTime() - date2.getTime(); Date myDate = new Date(difference); 

To show the date:

 String diff = df.format(myDate); 
+1
source share

You need to first convert the strings to java.util.Date objects (e.g. using SimpleDateFormat.parse(String) ). You can then use Date.getTime() for each of the two Date instances you Date.getTime() and calculate the difference in milliseconds, or use the java.util.Calendar or joda time API for advanced calculations.

+1
source share

try this one

you can calculate days, hours and minutes

 public class TimeUtils { public static final String HOURS = "hours"; public static final String MINUTES = "minutes"; public static final String DAYS = "days"; public static int findTheNumberBetween(String type, Date day1, Date day2) { long diff = day2.getTime() - day1.getTime(); switch (type) { case DAYS: return (int) TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS); case HOURS: return (int) TimeUnit.HOURS.convert(diff, TimeUnit.MILLISECONDS); case MINUTES: return (int) TimeUnit.MINUTES.convert(diff, TimeUnit.MILLISECONDS); } return 0; } } 

and use it as

  Date day1= TimeUtils.getDateTime("2016-12-08 02:06:14"); Date day2 = TimeUtils.getDateTime("2016-12-08 02:10:14"); Log.d(TAG, "The difference: "+TimeUtils.findTheNumberBetween(TimeUtils.MINUTES,day1,day2)); 
0
source share

TL; DR

 Duration.between( ZonedDateTime.of( LocalDate.parse( "26/02/2011" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) , LocalTime.parse( "11:00 AM" , DateTimeFormatter.ofPattern( "hh:mm a" ) ) , ZoneId.of( "America/Montreal" ) ) , ZonedDateTime.of( LocalDate.parse( "27/02/2011" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) , LocalTime.parse( "12:15 AM" , DateTimeFormatter.ofPattern( "hh:mm a" ) ) , ZoneId.of( "America/Montreal" ) ) ).toString() 

See live code at IdeOne.com .

Timezone

The question and other answers ignore the crucial time zone problem. You cannot calculate the elapsed time between two date strings without knowing the estimated time zone. For example, in places with daylight saving time (DST), at night cutting time, the day can be 23 hours or 25 hours, not 24 hours.

java.time

The modern way to do work with date is with the java.time classes. They supersede unpleasant old time classes such as java.util.Date and java.util.Calendar .

Local…

Parse the input strings first. They do not have any indication of the time zone, so we analyze them as Local… types Local…

Define a DateTimeFormatter to match string inputs. By the way, in the future, use standard ISO 8601 formats when serializing date and time values ​​in text.

 DateTimeFormatter df = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ); LocalDate ld = LocalDate.parse( "26/02/2011" , df ) ; 

ld.toString (): 2011-02-2011

 DateTimeFormatter tf = DateTimeFormatter.ofPattern( "hh:mm a" ); LocalTime lt = LocalTime.parse( "11:00 AM" , tf ) ; 

lt.toString (): 11:00:00

ZoneId

You need to know the time zone designed for your business scenario. I will arbitrarily choose it.

Specify the time zone name in continent/region format, such as America/Montreal , Africa/Casablanca or Pacific/Auckland . Never use an abbreviation of 3-4 characters, for example EST or IST , as they are not real time zones, and are not standardized or even unique (!).

 ZoneId z = ZoneId.of( "America/Montreal" ); 

ZonedDateTime

Apply the zone to get the ZonedDateTime .

 ZonedDateTime zdtStart = ZonedDateTime.of( ld , lt , z ); 

zdtStart.toString (): 2011-02-26T11: 00: 00-05: 00 [America / Montreal]

Duration

Do the same to get zdtStop . Calculate elapsed time as a time span that is not tied to a timeline in Duration .

 Duration d = Duration.between( zdtStart , zdtStop ); 

Call toString to generate a string in the standard ISO 8601 format for the duration : PnYnMnDTnHnMnS . P marks the beginning, while T divides the two parts.

 String output = d.toString(); 

d.toString (): PT13H15M

In Java 9 and later, call the to…Part methods to…Part access each component.


About java.time

The java.time framework is built into Java 8 and later. These classes supersede the nasty old legacy time classes such as java.util.Date , Calendar and SimpleDateFormat .

The Joda-Time project, now in maintenance mode , we recommend switching to the java.time classes.

To learn more, see the Oracle Tutorial . And search for qaru for many examples and explanations. JSR 310 specification .

Where to get java.time classes?

  • Java SE 8 and SE 9 and later
    • Built in.
    • Part of the standard Java API with integrated implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Most of the functionality of java.time is ported back to Java 6 and 7 in ThreeTen-Backport .
  • Android
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) specifically for Android.
    • See How to use ....

The ThreeTen-Extra project extends java.time with additional classes. This project is a proof of possible future additions to java.time. Here you can find useful classes such as Interval , YearWeek , YearQuarter and more .

0
source share

All Articles