How do I add one month to current date in Java?
Asked Answered
S

18

106

In Java how can I add one month to the current date?

Serene answered 5/2, 2011 at 6:4 Comment(1)
related How can I increment a date by one day in Java?Analogize
F
137
Calendar cal = Calendar.getInstance(); 
cal.add(Calendar.MONTH, 1);
Flowery answered 5/2, 2011 at 6:8 Comment(9)
thanx piyush , and what this cal date format, i need to store this in mysqlSerene
mysql data type for date is DATETIME.Serene
is this correct date format that cal return , that i can use to store in mysqlSerene
The question was different than what you are asking now. However, in MySQL you can use DATE_ADD function to perform the date arithmetics. Reference: dev.mysql.com/doc/refman/5.5/en/…Flowery
The Java code to add a month to current date in the desired format would be as shown below. Now, it's upto you to convert this String to a date and insert in into MYSql database. Note, that you can change the date format in DateFormat constructor or later in the MYSQL query using STR_TO_DATE(str, format) function. DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Calendar now = Calendar.getInstance(); now.add(Calendar.MONTH, 1); String dateString = formatter.format(now.getTime());Flowery
cant i manipulate the date fro jave to convert it into mysql format ?Serene
Sure. I have included the code above in order to accomplish that using the Date Format object in Java.Flowery
This is outdated now: #4905916Umbrian
public String addDays() { Date date = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.MONTH, 1); date = cal.getTime(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String strDate = formatter.format(date); return strDate; }Welcy
U
64

Java 8

LocalDate futureDate = LocalDate.now().plusMonths(1);
Umbrian answered 25/3, 2015 at 7:59 Comment(2)
To have java.util.Date: Date.from((LocalDate.now().plusMonths(1)).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant())Armand
It requires a minimum API level of 26. so top answer is betterPharos
D
39

You can make use of apache's commons lang DateUtils helper utility class.

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

You can download commons lang jar at http://commons.apache.org/proper/commons-lang/

Determiner answered 5/3, 2014 at 12:57 Comment(0)
B
34

tl;dr

LocalDate::plusMonths

Example:

LocalDate.now( )
         .plusMonths( 1 );

Better to specify time zone.

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

java.time

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Time team also advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

Date-only

If you want the date-only, use the LocalDate class.

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

today.toString(): 2017-01-23

Add a month.

LocalDate oneMonthLater = today.plusMonths( 1 );

oneMonthLater.toString(): 2017-02-23

Date-time

Perhaps you want a time-of-day along with the date.

First get the current moment in UTC with a resolution of nanoseconds.

Instant instant = Instant.now();

Adding a month means determining dates. And determining dates means applying a time zone. For any given moment, the date varies around the world with a new day dawning earlier to the east. So adjust that Instant into a time zone.

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

Now add your month. Let java.time handle Leap month, and the fact that months vary in length.

ZonedDateTime zdtMonthLater = zdt.plusMonths( 1 );

You might want to adjust the time-of-day to the first moment of the day when making this kind of calculation. That first moment is not always 00:00:00.0 so let java.time determine the time-of-day.

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

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

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. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?


Joda-Time

Update: The Joda-Time project is now in maintenance mode. Its team advises migration to the java.time classes. I am leaving this section intact for posterity.

The Joda-Time library offers a method to add months in a smart way.

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

You might want to focus on the day by adjust the time-of-day to the first moment of the day.

DateTime nextMonth = now.plusMonths( 1 ).withTimeAtStartOfDay();
Bedwarmer answered 1/8, 2014 at 6:25 Comment(0)
C
13
Calendar cal = Calendar.getInstance(); 
cal.add(Calendar.MONTH, 1);
java.util.Date dt = cal.getTime();
Cinchonize answered 29/10, 2014 at 10:14 Comment(0)
U
8

(adapted from Duggu)

public static Date addOneMonth(Date date)
{
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.MONTH, 1);
    return cal.getTime();
}
Unduly answered 2/10, 2014 at 7:20 Comment(0)
T
8

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

DateUtils.addMonths(new Date(),1);
Townsman answered 7/9, 2019 at 11:23 Comment(1)
Simple and easy solution.Saleswoman
C
6

Use calander and try this code.

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();
Carricarriage answered 31/5, 2016 at 5:14 Comment(0)
U
5
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 ;
}`
Ultramodern answered 5/4, 2017 at 21:39 Comment(3)
Can you provide some explanation as to what your code does rather than just a large code block?Chibcha
My code is more restrictive and more generic. More restritive because it handles only date (in the form of string) with the fixed format "MM/dd/yyyy" . Generic because, it enables you to add any among of positive month on your specified date.Parlay
So, if you have to have a less restrictive code that take any java.util.Date and render another java.util.Date after adding a month, see below : Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.MONTH,1); cal.getTime();Parlay
M
3

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)

Mayworm answered 22/4, 2016 at 11:27 Comment(2)
Don't forget to add 'L' suffix to number else if will be treated as simple int and will overflow to a negative number!Mouth
public static final long ONE_MONTH = 2592000000L;Execrable
U
2

This method returns the current date plus 1 month.

public Date  addOneMonth()  {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 1);
        return cal.getTime();
}`
Ultramodern answered 5/4, 2017 at 22:18 Comment(0)
S
2
 public Date addMonth(Date inputDate, int monthToAddNumber){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(inputDate);
        // Add 'monthToAddNumber' months to inputDate
        calendar.add(Calendar.MONTH, monthToAddNumber);
        return calendar.getTime();
    }
  

then call method:

addMonth(new Date(), 1)
Sweyn answered 28/6, 2022 at 7:41 Comment(1)
This will not work with leap years: ie adding one month on Feb 29, will return March 29 instead of the proper value.Estivation
D
2

Use the plusMonths() method of the LocalDate class for Java 8 and Higher Versions.

// Add one month to the current local date

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

// Add one month to any local date object

LocalDate localDate = LocalDate.parse("2022-02-14").plusMonths(1); // 2022-03-14

Reference: https://www.javaexercise.com/java/java-add-months-to-date

Danell answered 1/8, 2022 at 15:56 Comment(0)
B
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);
    }
Boyd answered 8/10, 2015 at 10:52 Comment(1)
FYI, the terribly troublesome date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.Bedwarmer
G
1

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);
Gym answered 25/7, 2017 at 10:39 Comment(1)
* @deprecated As of JDK version 1.1, * replaced by <code>Calendar.set(Calendar.MONTH, int month)</code>. As the Date.java says.Narthex
B
1
Date dateAfterOneMonth = new DateTime(System.currentTimeMillis()).plusMonths(1).toDate();
Bumper answered 21/11, 2018 at 11:26 Comment(0)
B
0

Constants are in Portuguese because yes, but javadoc is understandable enough.

Just call

Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
DateSumUtil.sumOneMonth(cal);

and that's that. Related code:

package you.project.your_package_utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

public class DateSumUtil {

    private static Integer[] meses31 = { 2, 4, 7, 9 };
    private static List<Integer> meses31List = Arrays.asList(meses31);
    private static SimpleDateFormat s = new SimpleDateFormat("dd/MM/yyyy");

    private static final int MES = Calendar.MONTH;
    private static final int ANO = Calendar.YEAR;
    private static final int DIA = Calendar.DAY_OF_MONTH;

    /**
     * Receives a date and adds one month. <br />
     * 
     * @param c date to receive an added month, as {@code java.util.Calendar}
     * @param dia day of month of the original month
     */
    public static void addOneMonth(Calendar c, int dia) throws ParseException {
    if (cal.get(MES) == 0) {            if (dia < 29)           cal.add(MES, 1);
        else {  if (cal.get(ANO) % 4 == 0) {    if (dia < 30)   cal.add(MES, 1);
                                                else            cal.setTime(s.parse("29/02/" + cal.get(ANO)));
                } else {                        if (dia < 29)   cal.add(MES, 1);
                                                else            cal.setTime(s.parse("28/02/" + cal.get(ANO)));
    }   }   } else if (meses31List.contains(cal.get(MES))) {
        if (dia < 31) {                                         cal.add(Calendar.MONTH, 1);
                                                                cal.set(DIA, dia);
        } else  cal.setTime(s.parse("30/" + (cal.get(MES) + 2) + "/" + cal.get(ANO)));
    } else {                                                    cal.add(MES, 1);
                                                                cal.set(DIA, dia);  }   
}
Bauer answered 3/9, 2021 at 12:7 Comment(0)
I
-3
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
Impermissible answered 18/9, 2019 at 8:11 Comment(1)
First of all the answer is wrong based on the OP. Second The OP was answered 8(!) years ago and third there are better ways to formatting a date output than using loads of strings.Poplin

© 2022 - 2024 — McMap. All rights reserved.