Programing

Java 캘린더를 사용하여 날짜에서 X 일을 빼는 방법은 무엇입니까?

lottogame 2020. 5. 26. 07:41
반응형

Java 캘린더를 사용하여 날짜에서 X 일을 빼는 방법은 무엇입니까?


누구나 Java 달력을 사용하여 날짜에서 X 일을 빼는 간단한 방법을 알고 있습니까?

Java에서 날짜에서 X 일을 직접 뺄 수있는 함수를 찾을 수 없었습니다. 누군가 올바른 방향으로 나를 가리킬 수 있습니까?


여기 문서 에서 가져온 :

캘린더 규칙에 따라 지정된 캘린더 필드에 지정된 시간을 더하거나 뺍니다. 예를 들어, 달력의 현재 시간에서 5 일을 빼려면 다음을 호출하여 달성 할 수 있습니다.

Calendar calendar = Calendar.getInstance(); // this would default to now
calendar.add(Calendar.DAY_OF_MONTH, -5).

add메소드를 사용하고 음수로 전달할 수 있습니다. 그러나 Calendar다음과 같은 클래스를 사용하지 않는 간단한 메소드를 작성할 수도 있습니다.

public static void addDays(Date d, int days)
{
    d.setTime( d.getTime() + (long)days*1000*60*60*24 );
}

이것은 날짜의 시간 소인 값 (에포크 이후 밀리 초)을 가져오고 적절한 밀리 초 수를 추가합니다. days 매개 변수에 음수를 전달하여 빼기를 수행 할 수 있습니다. 이것은 "적절한"캘린더 솔루션보다 간단합니다.

public static void addDays(Date d, int days)
{
    Calendar c = Calendar.getInstance();
    c.setTime(d);
    c.add(Calendar.DATE, days);
    d.setTime( c.getTime().getTime() );
}

이 두 가지 솔루션 모두 Date완전히 새로운을 반환하지 않고 매개 변수로 전달 객체를 변경합니다 Date. 원하는 경우 다른 방법으로 기능을 쉽게 변경할 수 있습니다.


Anson의 대답 은 간단한 경우에는 잘 작동하지만 더 복잡한 날짜 계산을 수행하려면 Joda Time을 확인하는 것이 좋습니다 . 그것은 당신의 인생을 훨씬 쉽게 만들어 줄 것입니다.

참고로 Joda Time에서 할 수있는 일

DateTime dt = new DateTime();
DateTime fiveDaysEarlier = dt.minusDays(5);

tl; dr

LocalDate.now().minusDays( 10 )

시간대를 지정하는 것이 좋습니다.

LocalDate.now( ZoneId.of( "America/Montreal" ) ).minusDays( 10 )

세부

java.util.Date/ 와 같은 초기 버전의 Java와 함께 제공되는 이전 날짜-시간 클래스 .Calendar는 번거롭고 혼란스럽고 결함이있는 것으로 입증되었습니다. 피하십시오.

java.time

Java 8 이상은 새로운 java.time 프레임 워크로 이전 클래스를 대체합니다. 튜토리얼을 참조하십시오 . JSR 310에 의해 정의되고 Joda-Time 에서 영감을 얻었으며 ThreeTen-Extra 프로젝트에 의해 확장되었습니다 . ThreeTen-Backport 프로젝트는 클래스를 Java 6 & 7로 백 포트합니다. ThreeTenABP 프로젝트를 Android로

날짜 만 요청하는지 또는 날짜-시간을 요구하는지 명확하지 않은 질문은 모호합니다.

LocalDate

시간이없는 날짜 전용 LocalDate클래스를 사용하십시오 . "오늘"과 같은 날짜를 결정하는 데 중요한 시간대가 있습니다.

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
LocalDate tenDaysAgo = today.minusDays( 10 );

ZonedDateTime

날짜-시간을 의미 한 경우 Instant클래스를 사용하여 UTC로 시간 표시 막대에 순간을 가져옵니다 . 거기에서 표준 시간대로 조정하여 ZonedDateTime개체 를 가져옵니다 .

Instant now = Instant.now();  // UTC.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
ZonedDateTime tenDaysAgo = zdt.minusDays( 10 );

최신 및 기존 Java의 날짜-시간 유형 테이블.


java.time에 대하여

java.time의 프레임 워크는 나중에 자바 8에 내장되어 있습니다. 이 클래스는 까다로운 기존에 대신 기존 과 같은 날짜 - 시간의 수업을 java.util.Date, Calendar, SimpleDateFormat.

Joda 타임 프로젝트는 지금에 유지 관리 모드 의로 마이그레이션을 조언 java.time의 클래스.

자세한 내용은 Oracle Tutorial을 참조하십시오 . 많은 예제와 설명을 보려면 스택 오버플로를 검색하십시오. 사양은 JSR 310 입니다.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


int x = -1;
Calendar cal = ...;
cal.add(Calendar.DATE, x);

edit: the parser doesn't seem to like the link to the Javadoc, so here it is in plaintext:

http://java.sun.com/j2se/1.4.2/docs/api/java/util/Calendar.html#add(int, int)


Instead of writing my own addDays as suggested by Eli, I would prefer to use DateUtils from Apache. It is handy especially when you have to use it multiple places in your project.

The API says:

addDays(Date date, int amount)

Adds a number of days to a date returning a new object.

Note that it returns a new Date object and does not make changes to the previous one itself.


Someone recommended Joda Time so - I have been using this CalendarDate class http://calendardate.sourceforge.net

It's a somewhat competing project to Joda Time, but much more basic at only 2 classes. It's very handy and worked great for what I needed since I didn't want to use a package bigger than my project. Unlike the Java counterparts, its smallest unit is the day so it is really a date (not having it down to milliseconds or something). Once you create the date, all you do to subtract is something like myDay.addDays(-5) to go back 5 days. You can use it to find the day of the week and things like that. Another example:

CalendarDate someDay = new CalendarDate(2011, 10, 27);
CalendarDate someLaterDay = today.addDays(77);

And:

//print 4 previous days of the week and today
String dayLabel = "";
CalendarDate today = new CalendarDate(TimeZone.getDefault());
CalendarDateFormat cdf = new CalendarDateFormat("EEE");//day of the week like "Mon"
CalendarDate currDay = today.addDays(-4);
while(!currDay.isAfter(today)) {
    dayLabel = cdf.format(currDay);
    if (currDay.equals(today))
        dayLabel = "Today";//print "Today" instead of the weekday name
    System.out.println(dayLabel);
    currDay = currDay.addDays(1);//go to next day
}

It can be done easily by the following

Calendar calendar = Calendar.getInstance();
        // from current time
        long curTimeInMills = new Date().getTime();
        long timeInMills = curTimeInMills - 5 * (24*60*60*1000);    // `enter code here`subtract like 5 days
        calendar.setTimeInMillis(timeInMills);
        System.out.println(calendar.getTime());

        // from specific time like (08 05 2015)
        calendar.set(Calendar.DAY_OF_MONTH, 8);
        calendar.set(Calendar.MONTH, (5-1));
        calendar.set(Calendar.YEAR, 2015);
        timeInMills = calendar.getTimeInMillis() - 5 * (24*60*60*1000);
        calendar.setTimeInMillis(timeInMills);
        System.out.println(calendar.getTime());

Eli Courtwright second solution is wrong, it should be:

Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, -days);
date.setTime(c.getTime().getTime());

참고URL : https://stackoverflow.com/questions/212321/how-to-subtract-x-days-from-a-date-using-java-calendar

반응형