How to calculate time difference in java?

后端 未结 17 1388
醉酒成梦
醉酒成梦 2020-11-22 16:33

I want to subtract two timeperiods say 16:00:00 from 19:00:00. Is there any java function for this? The results can be in milliseconds, seconds, or minutes.

相关标签:
17条回答
  • 2020-11-22 16:59

    The painful way is to convert to millis and do the subtraction and then back to whatever seconds or so you want. The better way is to use JodaTime.

    0 讨论(0)
  • 2020-11-22 16:59
    import java.sql.*;
    
    class Time3 {
    
        public static void main(String args[]){ 
            String time1 = "01:03:23";
            String time2 = "02:32:00";
            long difference ;
            Time t1 = Time.valueOf(time1);
            Time t2 = Time.valueOf(time2);
            if(t2.getTime() >= t1.getTime()){
                difference = t2.getTime() - t1.getTime() -19800000;
            }
            else{
                difference = t1.getTime() - t2.getTime() -19800000;
            }
    
            java.sql.Time time = new java.sql.Time(difference); 
            System.out.println(time);
        } 
    
    } 
    
    0 讨论(0)
  • 2020-11-22 17:01
    public class timeDifference {
    
    public static void main(String[] args) {
    
        try {
    
            Date startTime = Calendar.getInstance().getTime();
            Thread.sleep(10000);
            Date endTime = Calendar.getInstance().getTime();
    
            long difference = endTime.getTime() - startTime.getTime();
    
            long differenceSeconds = difference / 1000 % 60;
            long differenceMinutes = difference / (60 * 1000) % 60;
            long differenceHours = difference / (60 * 60 * 1000) % 24;
            long differenceDays = difference / (24 * 60 * 60 * 1000);
    
            System.out.println(differenceDays + " days, ");
            System.out.println(differenceHours + " hours, ");
            System.out.println(differenceMinutes + " minutes, ");
            System.out.println(differenceSeconds + " seconds.");
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    }

    0 讨论(0)
  • 2020-11-22 17:02

    Besides the most common approach with Period and Duration objects you can widen your knowledge with another way for dealing with time in Java.

    Advanced Java 8 libraries. ChronoUnit for Differences.

    ChronoUnit is a great way to determine how far apart two Temporal values are. Temporal includes LocalDate, LocalTime and so on.

    LocalTime one = LocalTime.of(5,15);
    LocalTime two = LocalTime.of(6,30);
    LocalDate date = LocalDate.of(2019, 1, 29);
    
    System.out.println(ChronoUnit.HOURS.between(one, two)); //1
    System.out.println(ChronoUnit.MINUTES.between(one, two)); //75
    System.out.println(ChronoUnit.MINUTES.between(one, date)); //DateTimeException
    

    First example shows that between truncates rather than rounds.

    The second shows how easy it is to count different units.

    And the last example reminds us that we should not mess up with dates and times in Java :)

    0 讨论(0)
  • 2020-11-22 17:04

    class TimeCalculator { String updateTime;

         public TimeCalculator(String time)
          {
            // time should be in 24 hours format like 15/06/2016 17:39:20  
            this.updateTime = time;
          }
    
         public String getTimeDifference()
         {
            String td=null;
           // get Current Time
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
            Date currentDate = new Date();
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(currentDate);
    
            int c_year = calendar.get(Calendar.YEAR);
            int c_month = calendar.get(Calendar.MONTH) + 1;
            int c_day = calendar.get(Calendar.DAY_OF_MONTH);
    
            // get Editing Time
    
            Date edit_date = sdf.parse(updateTime);
            Calendar edit_calendar = new GregorianCalendar();
            edit_calendar.setTime(edit_date);
    
            int e_year = edit_calendar.get(Calendar.YEAR);
            int e_month = edit_calendar.get(Calendar.MONTH) + 1;
            int e_day = edit_calendar.get(Calendar.DAY_OF_MONTH);
    
    
            if(e_year==c_year&&e_month==c_month&&e_day==c_day)
                {
    
                 int c_hours = calendar.get(Calendar.HOUR_OF_DAY);
                 int c_minutes = calendar.get(Calendar.MINUTE);
                 int c_seconds = calendar.get(Calendar.SECOND);
    
                 int e_hours = edit_calendar.get(Calendar.HOUR_OF_DAY);
                 int e_minutes = edit_calendar.get(Calendar.MINUTE);
                 int e_seconds = edit_calendar.get(Calendar.SECOND);
    
          if(c_hours==e_hours&&c_minutes==e_minutes&&c_seconds==e_seconds)
             {
               td = "just now";
               return td;
              }
          else if(c_hours==e_hours&&c_minutes==e_minutes)
           {
             int d_seconds = c_seconds-e_seconds;
             td = String.valueOf(d_seconds);
             td = td+" seconds ago";
             return td;
           }
          else if(c_hours==e_hours&&c_minutes!=e_minutes)
           {
             int d_minutes = c_minutes-e_minutes;
             int d_seconds;
             if(c_seconds>e_seconds)
               {
                 d_seconds = c_seconds-e_seconds;
               }else{
                 d_seconds = e_seconds-c_seconds;
           }
              td = "00:"+String.valueOf(d_minutes)+":"+String.valueOf(d_seconds)+" ago";
            return td;
      }
        else
           {
            int d_minutes,d_seconds,d_hours;
            d_hours=c_hours-e_hours;
            if(c_minutes>e_minutes)
           {
             d_minutes = c_minutes-e_minutes;
           }else{
             d_minutes = e_minutes-c_minutes;
           }
            if(c_seconds>e_seconds)
              {
                d_seconds = c_seconds-e_seconds;
              }else{
                d_seconds = e_seconds-c_seconds;
              }
    
          td = String.valueOf(d_hours)+":"+String.valueOf(d_minutes)+":"+String.valueOf(d_seconds)+" ago";
         return td;
      }
    }
     else if(e_year==c_year&&e_month==c_month&&c_day==e_day+1){
       td = "yesterday";
       return td;
     }
     else{
        td = updateTime;
        return td;
         }
    }}
    
    0 讨论(0)
  • 2020-11-22 17:06

    I found this more cleaner.

           Date start = new Date();
            //Waiting for 10 seconds
            Thread.sleep(10000);
            Date end = new Date();
            long diff = end.getTime() - start.getTime();
            String TimeTaken = String.format("[%s] hours : [%s] mins : [%s] secs",
                    Long.toString(TimeUnit.MILLISECONDS.toHours(diff)), 
                    TimeUnit.MILLISECONDS.toMinutes(diff),
                    TimeUnit.MILLISECONDS.toSeconds(diff));
            System.out.println(String.format("Time taken %s", TimeTaken));
    

    Output : Time taken [0] hours : [0] mins : [10] secs

    0 讨论(0)
提交回复
热议问题