source

자바에서 시차를 계산하려면 어떻게 해야 하나요?

manysource 2022. 11. 23. 20:22

자바에서 시차를 계산하려면 어떻게 해야 하나요?

19:00:00부터 16:00:00라는 두 시간을 빼고 싶습니다.이것에 자바 기능이 있나요?결과는 밀리초, 초 또는 분 단위로 표시됩니다.

Java 8은 보다 깔끔한 솔루션 - Instant and Duration

예:

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

차이는 밀리초 단위입니다.

sfaiz 게시물을 수정했습니다.

타이밍을 잘 맞추려면

// 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.");

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

다른 언어와 마찬가지로 기간을 Unix 타임스탬프(Unix Epoch 이후 초)로 변환한 다음 단순히 빼기만 하면 됩니다.그런 다음 생성된 초를 새로운 unix 타임스탬프로 사용하여 원하는 형식으로 읽기 형식을 지정해야 합니다.

아, 위의 포스터(genesiss)에 적절한 신용을 부여해 주세요.코드는 항상 편리합니다.)하지만, 지금 설명도 있습니다.

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.

그리고 더 나은 형식으로 표시하려면 다음을 사용할 수 있습니다.

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

Period 객체와 Duration 객체에 대한 가장 일반적인 접근법 외에도 Java에서 시간을 처리하는 다른 방법으로 지식을 넓힐 수 있습니다.

고도의 Java 8 라이브러리.Chrono Unit의 차이점

ChronoUnit은 두 시간 값이 얼마나 떨어져 있는지를 판단하는 좋은 방법입니다.Temporal에는 LocalDate, LocalTime 등이 포함됩니다.

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

첫 번째 예시는 반올림이 아닌 잘라내기 사이의 예를 보여줍니다.

두 번째는 다른 단위를 계산하는 것이 얼마나 쉬운지를 보여줍니다.

그리고 마지막 예에서는 Java에서 날짜와 시간을 혼동하지 않도록 주의해 주십시오.

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

청소기를 찾았어요.

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

산출량

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

고통스러운 방법은 밀리스로 변환하고 뺄셈을 한 다음 원하는 초 정도로 되돌리는 것입니다.좋은 방법은 Joda Time을 사용하는 것입니다.

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; 

이제 분수는 두 시간 사이의 올바른 기간이 됩니다(분).

Java 8 Local Time을 사용하면 쉽게 실행할 수 있습니다.

String time1 = "16:00:00";
String time2 = "19:00:00";

long seconds = Duration.between(LocalTime.parse(time1), LocalTime.parse(time2)).getSeconds()

지속시간은 getSeconds() 대신 밀리초 또는 분을 얻기 위해 사용할 수 있는 toMillis()와 toMinutes()도 지원합니다.

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

예외 핸들 해석 예외가 발생합니다.

§ 다른 요일의 시간을 사용하는 경우의 lternative 옵션(예: 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);
    }

이것을 시험해 보세요.

public String timeDifference8(String startTime, String endTime) {
    LocalTime initialTime = LocalTime.parse(startTime);
    LocalTime finalTime =LocalTime.parse(endTime);
    StringJoiner joiner = new StringJoiner(":");
    long hours = initialTime.until( finalTime, ChronoUnit.HOURS);
    initialTime = initialTime.plusHours( hours );
    long minutes = initialTime.until(finalTime, ChronoUnit.MINUTES);
    initialTime = initialTime.plusMinutes( minutes );
    long seconds = initialTime.until( finalTime, ChronoUnit.SECONDS);
    joiner.add(String.valueOf(hours));
    joiner.add(String.valueOf(minutes));
    joiner.add(String.valueOf(seconds));
    return joiner.toString();
}
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);
    } 

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

}

Instant 사용

        Instant start = Instant.parse("2017-10-03T10:15:30.00Z");
        Instant end = Instant.parse("2017-10-04T11:35:31.00Z");

        long duration = Duration.between(start, end).toMillis();
        long minutes = TimeUnit.MILLISECONDS.toMinutes(duration)*60;
        String time = String.format("%02d hours, %02d min, %02d sec",
                TimeUnit.MILLISECONDS.toHours(duration),
                TimeUnit.MILLISECONDS.toMinutes(duration) -  TimeUnit.MILLISECONDS.toHours(duration) * 60,
                TimeUnit.MILLISECONDS.toSeconds(duration) - minutes);
                       ;
        System.out.println("time = " + time);

언급URL : https://stackoverflow.com/questions/4927856/how-can-i-calculate-a-time-difference-in-java