Programing

자바, 두 날짜 사이의 일 수 계산

lottogame 2020. 11. 29. 09:32
반응형

자바, 두 날짜 사이의 일 수 계산


이 질문에 이미 답변이 있습니다.

중복 가능성 :
두 Java 날짜 인스턴스 간의 차이 계산

Java에서 두 날짜 사이의 일 수를 계산하고 싶습니다.

내 데이터베이스에서는 DATE데이터 유형 으로 저장 되지만 내 코드에서는 문자열입니다.

이 두 문자열 사이의 일 수를 계산하고 싶습니다.


우선, 필요한 경우에만 문자열로 처리해야합니다. 대부분의 경우 작업중인 데이터를 실제로 설명하는 데이터 유형으로 작업해야합니다.

/ 보다 훨씬 나은 API 인 Joda Time 을 사용하는 것이 좋습니다 . 이 경우 유형을 사용해야하는 것 같습니다. 그런 다음 다음을 사용할 수 있습니다.DateCalendarLocalDate

int days = Days.daysBetween(date1, date2).getDays();

Java 8에서의 인스턴스를 사용 Enum ChronoUnit하여 다른 단위 (일, 월, 초)로 시간을 계산할 수 있습니다 .

예를 들면 :

ChronoUnit.DAYS.between(startDate,endDate)

이 코드를 시도

     Calendar cal1 = new GregorianCalendar();
     Calendar cal2 = new GregorianCalendar();

     SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");

     Date date = sdf.parse("your first date");
     cal1.setTime(date)
     date = sdf.parse("your second date");
     cal2.setTime(date);

    //cal1.set(2008, 8, 1); 
     //cal2.set(2008, 9, 31);
     System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));

이 기능

     public int daysBetween(Date d1, Date d2){
             return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
     }

이 스레드가 이제 2 년이 된 것을 알고 있지만 여전히 여기에서 정답을 볼 수 없습니다.

Joda를 사용하거나 Java 8을 사용하지 않고 일광 절약 시간의 영향을받는 날짜를 빼야하는 경우를 제외하고.

그래서 나는 내 자신의 솔루션을 작성했습니다. 중요한 측면은 시간 정보를 버릴 필요가 있기 때문에 실제로 날짜에만 관심이있을 때만 작동한다는 것입니다. 따라서와 같은 것을 원한다면 25.06.2014 - 01.01.2010 = 1636DST에 관계없이 작동해야합니다.

private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy");

public static long getDayCount(String start, String end) {
  long diff = -1;
  try {
    Date dateStart = simpleDateFormat.parse(start);
    Date dateEnd = simpleDateFormat.parse(end);

    //time is always 00:00:00, so rounding should help to ignore the missing hour when going from winter to summer time, as well as the extra hour in the other direction
    diff = Math.round((dateEnd.getTime() - dateStart.getTime()) / (double) 86400000);
  } catch (Exception e) {
    //handle the exception according to your own situation
  }
  return diff;
}

시간이 항상 그렇듯이 00:00:00double을 사용 Math.round()하면 겨울에서 여름으로 이동할 때 누락 된 3600000ms (1 시간)를 무시하고 여름에서 겨울로 이동하는 경우 추가 시간을 무시하는 데 도움이됩니다.

이것은 증명하기 위해 사용하는 작은 JUnit4 테스트입니다.

@Test
public void testGetDayCount() {
  String startDateStr = "01.01.2010";
  GregorianCalendar gc = new GregorianCalendar(locale);
  try {
    gc.setTime(simpleDateFormat.parse(startDateStr));
  } catch (Exception e) {
  }

  for (long i = 0; i < 10000; i++) {
    String dateStr = simpleDateFormat.format(gc.getTime());
    long dayCount = getDayCount(startDateStr, dateStr);
    assertEquals("dayCount must be equal to the loop index i: ", i, dayCount);
    gc.add(GregorianCalendar.DAY_OF_YEAR, 1);
  }
}

... 또는 그것이 '생명'하는 것을보고 싶다면 단언을 다음과 같이 바꾸십시오.

System.out.println("i: " + i + " | " + dayCount + " - getDayCount(" + startDateStr + ", " + dateStr + ")");

... 출력은 다음과 같습니다.

  i: 0 | 0  - getDayCount(01.01.2010, 01.01.2010)
  i: 1 | 1  - getDayCount(01.01.2010, 02.01.2010)
  i: 2 | 2  - getDayCount(01.01.2010, 03.01.2010)
  i: 3 | 3  - getDayCount(01.01.2010, 04.01.2010)
  ...
  i: 1636 | 1636  - getDayCount(01.01.2010, 25.06.2014)
  ...
  i: 9997 | 9997  - getDayCount(01.01.2010, 16.05.2037)
  i: 9998 | 9998  - getDayCount(01.01.2010, 17.05.2037)
  i: 9999 | 9999  - getDayCount(01.01.2010, 18.05.2037)

여기에 도움이 될 수있는 작은 프로그램이 있습니다.

import java.util.*;

public class DateDifference {
    public static void main(String args[]){
        DateDifference difference = new DateDifference();
    }

    DateDifference() {
        Calendar cal1 = new GregorianCalendar();
        Calendar cal2 = new GregorianCalendar();

        cal1.set(2010, 12, 1); 
        cal2.set(2011, 9, 31);
        System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));
    }

    public int daysBetween(Date d1, Date d2) {
        return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
    }
}

// http://en.wikipedia.org/wiki/Julian_day
public static int julianDay(int year, int month, int day) {
  int a = (14 - month) / 12;
  int y = year + 4800 - a;
  int m = month + 12 * a - 3;
  int jdn = day + (153 * m + 2)/5 + 365*y + y/4 - y/100 + y/400 - 32045;
  return jdn;
}

public static int diff(int y1, int m1, int d1, int y2, int m2, int d2) {
  return julianDay(y1, m1, d1) - julianDay(y2, m2, d2);
}

저는 정말로 Java를 처음 접하기 때문에 제가 제안하는 일을 할 수있는 더 좋은 방법이 있다고 확신합니다.

나는 동일한 요구를 가지고 있었고 두 날짜의 DAYOFYEAR의 차이를 사용하여 수행했습니다. 더 쉬운 방법 인 것 같았습니다 ...

성능 및 안정성 측면에서이 솔루션을 실제로 평가할 수는 없지만 괜찮다고 생각합니다.

여기:

    public static void main(String[] args) throws ParseException {



//Made this part of the code just to create the variables i'll use.
//I'm in Brazil and the date format here is DD/MM/YYYY, but wont be an issue to you guys. 
//It will work anyway with your format.

    String s1 = "18/09/2014"; 
    String s2 = "01/01/2014";
    DateFormat f = DateFormat.getDateInstance();
    Date date1 = f.parse(s1); 
    Date date2 = f.parse(s2);




//Here's the part where we get the days between two dates.

    Calendar day1 = Calendar.getInstance();
    Calendar day2 = Calendar.getInstance(); 
    day1.setTime(date1);
    day2.setTime(date2);

    int daysBetween = day1.get(Calendar.DAY_OF_YEAR) - day2.get(Calendar.DAY_OF_YEAR);      




//Some code just to show the result...
    f = DateFormat.getDateInstance(DateFormat.MEDIUM);
    System.out.println("There's " + daysBetween + " days between " + f.format(day1.getTime()) + " and " + f.format(day2.getTime()) + ".");



    }

In this case, the output would be (remembering that i'm using the Date Format DD/MM/YYYY):

There's 260 days between 18/09/2014 and 01/01/2014.

This function is good for me:

public static int getDaysCount(Date begin, Date end) {
    Calendar start = org.apache.commons.lang.time.DateUtils.toCalendar(begin);
    start.set(Calendar.MILLISECOND, 0);
    start.set(Calendar.SECOND, 0);
    start.set(Calendar.MINUTE, 0);
    start.set(Calendar.HOUR_OF_DAY, 0);

    Calendar finish = org.apache.commons.lang.time.DateUtils.toCalendar(end);
    finish.set(Calendar.MILLISECOND, 999);
    finish.set(Calendar.SECOND, 59);
    finish.set(Calendar.MINUTE, 59);
    finish.set(Calendar.HOUR_OF_DAY, 23);

    long delta = finish.getTimeInMillis() - start.getTimeInMillis();
    return (int) Math.ceil(delta / (1000.0 * 60 * 60 * 24));
}

My best solution (so far) for calculating the number of days difference:

//  This assumes that you already have two Date objects: startDate, endDate
//  Also, that you want to ignore any time portions

Calendar startCale=new GregorianCalendar();
Calendar endCal=new GregorianCalendar();

startCal.setTime(startDate);
endCal.setTime(endDate);

endCal.add(Calendar.YEAR,-startCal.get(Calendar.YEAR));
endCal.add(Calendar.MONTH,-startCal.get(Calendar.Month));
endCal.add(Calendar.DATE,-startCal.get(Calendar.DATE));

int daysDifference=endCal.get(Calendar.DAY_OF_YEAR);

Note, however, that this assumes less than a year's difference!


If you're sick of messing with java you can just send it to db2 as part of your query:

select date1, date2, days(date1) - days(date2) from table

will return date1, date2 and the difference in days between the two.

참고URL : https://stackoverflow.com/questions/7103064/java-calculate-the-number-of-days-between-two-dates

반응형