如何计算java中的时差?

时间:2022-01-28 21:19:44

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.

我想从19:00:00减去两个时间段16:00:00。这有什么java功能吗?结果可以是毫秒,秒或分钟。

13 个解决方案

#1


94  

String time1 = "16:00:00";
String time2 = "19: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(); 

Difference is in milliseconds.

差异以毫秒为单位。

I modified sfaizs post.

我修改了sfaizs帖子。

#2


50  

Java 8 has a cleaner solution - Instant and Duration

Java 8有一个更清洁的解决方案 - 即时和持续时间

Example:

例:

import java.time.Duration;
import java.time.Instant;
...
Instant start = Instant.now();
//your code
Instant end = Instant.now();
Duration timeElapsed = Duration.between(start, end);
System.out.println("Time taken: "+ timeElapsed.toMillis() +" milliseconds");

#3


30  

TO get pretty timing differences, then

那么,获得相当不同的时间差异

// d1, d2 are dates
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.");

#4


27  

Java 8

Java 8

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

LocalDateTime dateTime1= LocalDateTime.parse("2014-11-25 19:00:00", formatter);
LocalDateTime dateTime2= LocalDateTime.parse("2014-11-25 16:00:00", formatter);

long diffInMilli = java.time.Duration.between(dateTime1, dateTime2).toMillis();
long diffInSeconds = java.time.Duration.between(dateTime1, dateTime2).getSeconds();
long diffInMinutes = java.time.Duration.between(dateTime1, dateTime2).toMinutes();

#5


11  

Just like any other language; convert your time periods to a unix timestamp (ie, seconds since the Unix epoch) and then simply subtract. Then, the resulting seconds should be used as a new unix timestamp and read formatted in whatever format you want.

就像任何其他语言一样;将你的时间段转换为unix时间戳(即自Unix纪元以来的秒数),然后简单地减去。然后,生成的秒应该用作新的unix时间戳,并以您想要的任何格式读取格式。

Ah, give the above poster (genesiss) his due credit, code's always handy ;) Though, you now have an explanation as well :)

啊,给上面的海报(genesiss)他应得的信誉,代码总是很方便;)虽然,你现在也有一个解释:)

#6


6  

import java.util.Date;
...
Date d1 = new Date();
...
...
Date d2 = new Date();
System.out.println(d2.getTime()-d1.getTime()); //gives the time difference in milliseconds. 
System.out.println((d2.getTime()-d1.getTime())/1000); //gives the time difference in seconds.

and, to show in a nicer format, you can use:

并且,为了以更好的格式显示,您可以使用:

    DecimalFormat myDecimalFormatter = new DecimalFormat("###,###.###");
    System.out.println(myDecimalFormatter.format(((double)d2.getTime()-d1.getTime())/1000));

#7


2  

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.

痛苦的方法是转换为millis并进行减法,然后回到你想要的任何秒数。更好的方法是使用JodaTime。

#8


1  

Аlternative option if time from different days is taken, for example: 22:00 and 01:55.

如果从不同日期开始计时,则选择备选方案,例如:22:00和01:55。

public static long getDiffTime(Date date1, Date date2){
        if (date2.getTime() - date1.getTime() < 0) {// if for example date1 = 22:00, date2 = 01:55.
            Calendar c = Calendar.getInstance();
            c.setTime(date2);
            c.add(Calendar.DATE, 1);
            date2 = c.getTime();
        } //else for example date1 = 01:55, date2 = 03:55.
        long ms = date2.getTime() - date1.getTime();

        //235 minutes ~ 4 hours for (22:00 -- 01:55).
        //120 minutes ~ 2 hours for (01:55 -- 03:55).
        return TimeUnit.MINUTES.convert(ms, TimeUnit.MILLISECONDS);
    }

#9


1  

String start = "12:00:00";
String end = "02:05:00";

SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); 

Date date1 = format.parse(start);

Date date2 = format.parse(end);

long difference = date2.getTime() - date1.getTime(); 

int minutes = (int) TimeUnit.MILLISECONDS.toMinutes(difference);

if(minutes<0)minutes += 1440; 

Now minutes will be the correct duration between two time (in minute).

现在分钟将是两次(以分钟为单位)之间的正确持续时间。

#10


1  

import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws Exception{
    String time1 = "12:00:00";
    String time2 = "12:01:00";
    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
    Date date1 = format.parse(time1);
    Date date2 = format.parse(time2);
    long difference = date2.getTime() - date1.getTime();
    System.out.println(difference/1000);
}}

throws exception handles parsing exceptions

抛出异常处理解析异常

#11


0  

    /*
 * Total time calculation.
 */
private void getTotalHours() {
    try {
        // TODO Auto-generated method stub
        if (tfTimeIn.getValue() != null && tfTimeOut.getValue() != null) {
            Long min1 = tfTimeOut.getMinutesValue();
            Long min2 = tfTimeIn.getMinutesValue();
            Long hr1 = tfTimeOut.getHoursValue();
            Long hr2 = tfTimeIn.getHoursValue();
            Long hrsTotal = new Long("0");
            Long minTotal = new Long("0");
            if ((hr2 - hr1) == 1) {
                hrsTotal = (long) 1;
                if (min1 != 0 && min2 == 0) {
                    minTotal = (long) 60 - min1;
                } else if (min1 == 0 && min2 != 0) {
                    minTotal = min2;
                } else if (min1 != 0 && min2 != 0) {
                    minTotal = min2;
                    Long minOne = (long) 60 - min1;
                    Long minTwo = min2;
                    minTotal = minOne + minTwo;
                }
                if (minTotal >= 60) {
                    hrsTotal++;
                    minTotal = minTotal % 60;
                }
            } else if ((hr2 - hr1) > 0) {
                hrsTotal = (hr2 - hr1);
                if (min1 != 0 && min2 == 0) {
                    minTotal = (long) 60 - min1;
                } else if (min1 == 0 && min2 != 0) {
                    minTotal = min2;
                } else if (min1 != 0 && min2 != 0) {
                    minTotal = min2;
                    Long minOne = (long) 60 - min1;
                    Long minTwo = min2;
                    minTotal = minOne + minTwo;
                }
                if (minTotal >= 60) {
                    minTotal = minTotal % 60;
                }
            } else if ((hr2 - hr1) == 0) {
                if (min1 != 0 || min2 != 0) {
                    if (min2 > min1) {
                        hrsTotal = (long) 0;
                        minTotal = min2 - min1;
                    } else {
                        Notification.show("Enter A Valid Time");
                        tfTotalTime.setValue("00.00");
                    }
                }
            } else {
                Notification.show("Enter A Valid Time");
                tfTotalTime.setValue("00.00");
            }
            String hrsTotalString = hrsTotal.toString();
            String minTotalString = minTotal.toString();
            if (hrsTotalString.trim().length() == 1) {
                hrsTotalString = "0" + hrsTotalString;
            }
            if (minTotalString.trim().length() == 1) {
                minTotalString = "0" + minTotalString;
            }
            tfTotalTime.setValue(hrsTotalString + ":" + minTotalString);
        } else {
            tfTotalTime.setValue("00.00");
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

#12


0  

class TimeCalculator { String updateTime;

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;
     }
}}

#13


0  

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

}

}

#1


94  

String time1 = "16:00:00";
String time2 = "19: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(); 

Difference is in milliseconds.

差异以毫秒为单位。

I modified sfaizs post.

我修改了sfaizs帖子。

#2


50  

Java 8 has a cleaner solution - Instant and Duration

Java 8有一个更清洁的解决方案 - 即时和持续时间

Example:

例:

import java.time.Duration;
import java.time.Instant;
...
Instant start = Instant.now();
//your code
Instant end = Instant.now();
Duration timeElapsed = Duration.between(start, end);
System.out.println("Time taken: "+ timeElapsed.toMillis() +" milliseconds");

#3


30  

TO get pretty timing differences, then

那么,获得相当不同的时间差异

// d1, d2 are dates
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.");

#4


27  

Java 8

Java 8

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

LocalDateTime dateTime1= LocalDateTime.parse("2014-11-25 19:00:00", formatter);
LocalDateTime dateTime2= LocalDateTime.parse("2014-11-25 16:00:00", formatter);

long diffInMilli = java.time.Duration.between(dateTime1, dateTime2).toMillis();
long diffInSeconds = java.time.Duration.between(dateTime1, dateTime2).getSeconds();
long diffInMinutes = java.time.Duration.between(dateTime1, dateTime2).toMinutes();

#5


11  

Just like any other language; convert your time periods to a unix timestamp (ie, seconds since the Unix epoch) and then simply subtract. Then, the resulting seconds should be used as a new unix timestamp and read formatted in whatever format you want.

就像任何其他语言一样;将你的时间段转换为unix时间戳(即自Unix纪元以来的秒数),然后简单地减去。然后,生成的秒应该用作新的unix时间戳,并以您想要的任何格式读取格式。

Ah, give the above poster (genesiss) his due credit, code's always handy ;) Though, you now have an explanation as well :)

啊,给上面的海报(genesiss)他应得的信誉,代码总是很方便;)虽然,你现在也有一个解释:)

#6


6  

import java.util.Date;
...
Date d1 = new Date();
...
...
Date d2 = new Date();
System.out.println(d2.getTime()-d1.getTime()); //gives the time difference in milliseconds. 
System.out.println((d2.getTime()-d1.getTime())/1000); //gives the time difference in seconds.

and, to show in a nicer format, you can use:

并且,为了以更好的格式显示,您可以使用:

    DecimalFormat myDecimalFormatter = new DecimalFormat("###,###.###");
    System.out.println(myDecimalFormatter.format(((double)d2.getTime()-d1.getTime())/1000));

#7


2  

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.

痛苦的方法是转换为millis并进行减法,然后回到你想要的任何秒数。更好的方法是使用JodaTime。

#8


1  

Аlternative option if time from different days is taken, for example: 22:00 and 01:55.

如果从不同日期开始计时,则选择备选方案,例如:22:00和01:55。

public static long getDiffTime(Date date1, Date date2){
        if (date2.getTime() - date1.getTime() < 0) {// if for example date1 = 22:00, date2 = 01:55.
            Calendar c = Calendar.getInstance();
            c.setTime(date2);
            c.add(Calendar.DATE, 1);
            date2 = c.getTime();
        } //else for example date1 = 01:55, date2 = 03:55.
        long ms = date2.getTime() - date1.getTime();

        //235 minutes ~ 4 hours for (22:00 -- 01:55).
        //120 minutes ~ 2 hours for (01:55 -- 03:55).
        return TimeUnit.MINUTES.convert(ms, TimeUnit.MILLISECONDS);
    }

#9


1  

String start = "12:00:00";
String end = "02:05:00";

SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); 

Date date1 = format.parse(start);

Date date2 = format.parse(end);

long difference = date2.getTime() - date1.getTime(); 

int minutes = (int) TimeUnit.MILLISECONDS.toMinutes(difference);

if(minutes<0)minutes += 1440; 

Now minutes will be the correct duration between two time (in minute).

现在分钟将是两次(以分钟为单位)之间的正确持续时间。

#10


1  

import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws Exception{
    String time1 = "12:00:00";
    String time2 = "12:01:00";
    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
    Date date1 = format.parse(time1);
    Date date2 = format.parse(time2);
    long difference = date2.getTime() - date1.getTime();
    System.out.println(difference/1000);
}}

throws exception handles parsing exceptions

抛出异常处理解析异常

#11


0  

    /*
 * Total time calculation.
 */
private void getTotalHours() {
    try {
        // TODO Auto-generated method stub
        if (tfTimeIn.getValue() != null && tfTimeOut.getValue() != null) {
            Long min1 = tfTimeOut.getMinutesValue();
            Long min2 = tfTimeIn.getMinutesValue();
            Long hr1 = tfTimeOut.getHoursValue();
            Long hr2 = tfTimeIn.getHoursValue();
            Long hrsTotal = new Long("0");
            Long minTotal = new Long("0");
            if ((hr2 - hr1) == 1) {
                hrsTotal = (long) 1;
                if (min1 != 0 && min2 == 0) {
                    minTotal = (long) 60 - min1;
                } else if (min1 == 0 && min2 != 0) {
                    minTotal = min2;
                } else if (min1 != 0 && min2 != 0) {
                    minTotal = min2;
                    Long minOne = (long) 60 - min1;
                    Long minTwo = min2;
                    minTotal = minOne + minTwo;
                }
                if (minTotal >= 60) {
                    hrsTotal++;
                    minTotal = minTotal % 60;
                }
            } else if ((hr2 - hr1) > 0) {
                hrsTotal = (hr2 - hr1);
                if (min1 != 0 && min2 == 0) {
                    minTotal = (long) 60 - min1;
                } else if (min1 == 0 && min2 != 0) {
                    minTotal = min2;
                } else if (min1 != 0 && min2 != 0) {
                    minTotal = min2;
                    Long minOne = (long) 60 - min1;
                    Long minTwo = min2;
                    minTotal = minOne + minTwo;
                }
                if (minTotal >= 60) {
                    minTotal = minTotal % 60;
                }
            } else if ((hr2 - hr1) == 0) {
                if (min1 != 0 || min2 != 0) {
                    if (min2 > min1) {
                        hrsTotal = (long) 0;
                        minTotal = min2 - min1;
                    } else {
                        Notification.show("Enter A Valid Time");
                        tfTotalTime.setValue("00.00");
                    }
                }
            } else {
                Notification.show("Enter A Valid Time");
                tfTotalTime.setValue("00.00");
            }
            String hrsTotalString = hrsTotal.toString();
            String minTotalString = minTotal.toString();
            if (hrsTotalString.trim().length() == 1) {
                hrsTotalString = "0" + hrsTotalString;
            }
            if (minTotalString.trim().length() == 1) {
                minTotalString = "0" + minTotalString;
            }
            tfTotalTime.setValue(hrsTotalString + ":" + minTotalString);
        } else {
            tfTotalTime.setValue("00.00");
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

#12


0  

class TimeCalculator { String updateTime;

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;
     }
}}

#13


0  

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

}

}