Programing

Java에서 현재 날짜에 한 달을 어떻게 추가합니까?

crosscheck 2020. 10. 18. 08:24
반응형

Java에서 현재 날짜에 한 달을 어떻게 추가합니까?


Java에서 어떻게 현재 날짜에 한 달을 추가 할 수 있습니까?


Calendar cal = Calendar.getInstance(); 
cal.add(Calendar.MONTH, 1);

자바 8

LocalDate futureDate = LocalDate.now().plusMonths(1);

아파치의 공용 lang DateUtils 도우미 유틸리티 클래스를 사용할 수 있습니다.

Date newDate = DateUtils.addMonths(new Date(), 1);

http://commons.apache.org/proper/commons-lang/ 에서 commons lang jar를 다운로드 할 수 있습니다 .


tl; dr

LocalDate::plusMonths

예:

LocalDate.now( )
         .plusMonths( 1 );

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

LocalDate.now( ZoneId.of( "America/Montreal" )
         .plusMonths( 1 );

java.time

java.time의 프레임 워크는 나중에 자바 8에 내장되어 있습니다. 이 클래스는 다음과 같은 기존의 번잡 한 날짜 - 시간의 수업을 대신하는 java.util.Date, .Calendar, java.text.SimpleDateFormat. Joda 타임 팀은 java.time로 마이그레이션을 조언한다.

자세한 내용은 Oracle Tutorial을 참조하십시오 . 그리고 많은 예제와 설명을 위해 Stack Overflow를 검색하십시오.

많은 java.time 기능은 자바 6 7 백 포팅 ThreeTen - 백 포트 및 상기 안드로이드 적응 ThreeTenABP .

날짜 만

데이트 전용을 원한다면 LocalDate수업을 사용하십시오 .

ZoneId z = ZoneId.of( "America/Montreal" );
 LocalDate today = LocalDate.now( z );

today.toString () : 2017-01-23

한 달을 추가하십시오.

LocalDate oneMonthLater = today.plusMonths( 1 );

oneMonthLater.toString () : 2017-02-23

날짜 시간

날짜와 함께 시간을 원할 수 있습니다.

먼저 나노초 해상도로 UTC현재 순간을 가져옵니다 .

Instant instant = Instant.now();

한 달을 추가한다는 것은 날짜를 결정하는 것을 의미합니다. 그리고 날짜를 결정하는 것은 시간대를 적용하는 것을 의미합니다. 어느 순간이든, 날짜는 동쪽에서 더 일찍 새벽이 뜨면서 전 세계적으로 다양합니다. 그래서 그것을 Instant시간대로 조정하십시오 .

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

이제 월을 추가하십시오. java.time이 윤월을 처리하고 월의 길이가 다양하다는 사실을 확인하십시오.

ZonedDateTime zdtMonthLater = zdt.plusMonths( 1 );

이런 종류의 계산을 할 때 시간을 하루의 첫 번째 순간으로 조정할 수 있습니다. 그 첫 순간이 항상 그런 것은 00:00:00.0아니므로 java.time이 시간을 결정하도록하십시오.

ZonedDateTime zdtMonthLaterStartOfDay = zdtMonthLater.toLocalDate().atStartOfDay( zoneId );

java.time 정보

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

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

자세한 내용은 Oracle Tutorial을 참조하십시오 . 그리고 많은 예제와 설명을 위해 Stack Overflow를 검색하십시오. 사양은 JSR 310 입니다.

java.time 클래스는 어디서 구할 수 있습니까?

ThreeTen - 추가 프로젝트 추가 클래스와 java.time를 확장합니다. 이 프로젝트는 java.time에 향후 추가 될 수있는 가능성을 입증하는 곳입니다. 당신은 여기에 몇 가지 유용한 클래스와 같은 찾을 수 있습니다 Interval, YearWeek, YearQuarter, 그리고 .


Joda-Time

업데이트 : Joda-Time 프로젝트는 이제 유지 관리 모드입니다. 팀은 java.time 클래스로의 마이그레이션을 조언합니다. 이 섹션은 후손을 위해 그대로 둡니다.

Joda 타임 라이브러리는 현명한 방법으로 달을 추가 할 수있는 방법을 제공합니다.

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime now = DateTime.now( timeZone );
DateTime nextMonth = now.plusMonths( 1 );

시간을 하루의 첫 번째 순간으로 조정하여 하루에 집중할 수 있습니다.

DateTime nextMonth = now.plusMonths( 1 ).withTimeAtStartOfDay();

Calendar cal = Calendar.getInstance(); 
cal.add(Calendar.MONTH, 1);
java.util.Date dt = cal.getTime();

calander를 사용하고이 코드를 시도하십시오.

Calendar calendar = Calendar.getInstance();         
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date nextMonthFirstDay = calendar.getTime();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date nextMonthLastDay = calendar.getTime();

public Date  addMonths(String dateAsString, int nbMonths) throws ParseException {
        String format = "MM/dd/yyyy" ;
        SimpleDateFormat sdf = new SimpleDateFormat(format) ;
        Date dateAsObj = sdf.parse(dateAsString) ;
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateAsObj);
        cal.add(Calendar.MONTH, nbMonths);
        Date dateAsObjAfterAMonth = cal.getTime() ;
    System.out.println(sdf.format(dateAsObjAfterAMonth));
    return dateAsObjAfterAMonth ;
}`

(덕구 각색)

public static Date addOneMonth(Date date)
{
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.MONTH, 1);
    return cal.getTime();
}

If you need a one-liner (i.e. for Jasper Reports formula) and don't mind if the adjustment is not exactly one month (i.e "30 days" is enough):

new Date($F{invoicedate}.getTime() + 30L * 24L * 60L * 60L * 1000L)


You can use like this;

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String d = "2000-01-30";
Date date= new Date(sdf.parse(d).getTime());
date.setMonth(date.getMonth() + 1);

In order to find the day after one month, it is necessary to look at what day of the month it is today.

So if the day is first day of month run following code

Calendar calendar = Calendar.getInstance();

    Calendar calFebruary = Calendar.getInstance();
    calFebruary.set(Calendar.MONTH, Calendar.FEBRUARY);

    if (calendar.get(Calendar.DAY_OF_MONTH) == 1) {// if first day of month
    calendar.add(Calendar.MONTH, 1);
    calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
    Date nextMonthFirstDay = calendar.getTime();
    System.out.println(nextMonthFirstDay);

    }

if the day is last day of month, run following codes.

    else if ((calendar.getActualMaximum(Calendar.DAY_OF_MONTH) == calendar.get(Calendar.DAY_OF_MONTH))) {// if last day of month
    calendar.add(Calendar.MONTH, 1);
    calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
    Date nextMonthLastDay = calendar.getTime();
    System.out.println(nextMonthLastDay);
    }

if the day is in february run following code

    else if (calendar.get(Calendar.MONTH) == Calendar.JANUARY
            && calendar.get(Calendar.DAY_OF_MONTH) > calFebruary.getActualMaximum(Calendar.DAY_OF_MONTH)) {// control of february

    calendar.add(Calendar.MONTH, 1);
    calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
    Date nextMonthLastDay = calendar.getTime();
    System.out.println(nextMonthLastDay);

    }

the following codes are used for other cases.

    else { // any day
    calendar.add(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
    Date theNextDate = calendar.getTime();
    System.out.println(theNextDate);
    }

    Date dateAfterOneMonth = new DateTime(System.currentTimeMillis()).plusMonths(1).toDate();

This method returns the current date plus 1 month.

public Date  addOneMonth()  {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 1);
        return cal.getTime();
}`

you can use DateUtils class in org.apache.commons.lang3.time package

DateUtils.addMonths(new Date(),1);

public class StringSplit {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        date(5, 3);
        date(5, 4);
    }

    public static String date(int month, int week) {
        LocalDate futureDate = LocalDate.now().plusMonths(month).plusWeeks(week);
        String Fudate = futureDate.toString();
        String[] arr = Fudate.split("-", 3);
        String a1 = arr[0];
        String a2 = arr[1];
        String a3 = arr[2];
        String date = a3 + "/" + a2 + "/" + a1;
        System.out.println(date);
        return date;
    }
}

Output:

10/03/2020
17/03/2020

참고URL : https://stackoverflow.com/questions/4905416/how-do-i-add-one-month-to-current-date-in-java

반응형