Adding month to date in java

Add months to date

Opposite of subtracting months from a java date, this example will show how to add months to a date using java Calendar.add, java 8 date time api, joda’s DateTime.plusMonths and apache commons DateUtils.addMonths. Assuming players get a vacation after the super bowl, we will set the date which it occurred and then add one month to represent a vacation of sipping fruity drinks in Mexico.

Straight up Java

@Test public void add_months_to_date_in_java ()  Calendar superBowlXLV = Calendar.getInstance(); superBowlXLV.set(2011, 1, 6, 0, 0); Calendar sippinFruityDrinksInMexico = Calendar.getInstance(); sippinFruityDrinksInMexico.setTimeInMillis(superBowlXLV.getTimeInMillis()); sippinFruityDrinksInMexico.add(Calendar.MONTH, 1); SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"); logger.info(dateFormatter.format(superBowlXLV.getTime())); logger.info(dateFormatter.format(sippinFruityDrinksInMexico.getTime())); assertTrue(sippinFruityDrinksInMexico.after(superBowlXLV)); >
02/06/2011 00:00:49 CST 03/06/2011 00:00:49 CST

Java 8 Date and Time API

Java 8 LocalDateTime.plusMonths will return a copy of the LocalDateTime with the specified number of months added.

@Test public void add_months_to_date_in_java8()  LocalDateTime superBowlXLV = LocalDateTime.of(2011, Month.FEBRUARY, 6, 0, 0); LocalDateTime sippinFruityDrinksInMexico = superBowlXLV.plusMonths(1); java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter .ofPattern("MM/dd/yyyy HH:mm:ss S"); logger.info(superBowlXLV.format(formatter)); logger.info(sippinFruityDrinksInMexico.format(formatter)); assertTrue(sippinFruityDrinksInMexico.isAfter(superBowlXLV)); >
02/06/2011 00:00:00 0 03/06/2011 00:00:00 0

Joda Time

Joda DateTime.plusMonths will return a copy the DateTime plus the specified number of months.

@Test public void add_months_to_date_in_java_joda ()  DateTime superBowlXLV = new DateTime(2011, 2, 6, 0, 0, 0, 0); DateTime sippinFruityDrinksInMexico = superBowlXLV.plusMonths(1); DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss z"); logger.info(superBowlXLV.toString(fmt)); logger.info(sippinFruityDrinksInMexico.toString(fmt)); assertTrue(sippinFruityDrinksInMexico.isAfter(superBowlXLV)); >
02/06/2011 00:00:00 CST 03/06/2011 00:00:00 CST

Apache Commons

Apache commons DateUtils.addMonths will adds a number of months to the date returning a new object.

@Test public void add_months_to_date_in_java_apachecommons ()  Calendar superBowlXLV = Calendar.getInstance(); superBowlXLV.set(2011, 1, 6, 0, 0); Date sippinFruityDrinksInMexico = DateUtils.addMonths(superBowlXLV.getTime(), 1); SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"); logger.info(dateFormatter.format(superBowlXLV.getTime())); logger.info(dateFormatter.format(sippinFruityDrinksInMexico)); assertTrue(sippinFruityDrinksInMexico.after(superBowlXLV.getTime())); >
02/06/2011 00:00:11 CST 03/06/2011 00:00:11 CST

Add months to date posted by Justin Musgrove on 02 February 2014

Tagged: java, java-date, and java-date-math

Источник

Adding One Month to Current Date in Java

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this short tutorial, we’ll learn how to add one month to the current date in Java.

First, we’ll understand how to do this using core Java methods. Then, we’ll see how to accomplish the same using external libraries such as Joda-Time and Apache Commons Lang3.

2. Core Java Methods

Java provides several convenient ways to manipulate the date and time. Let’s explore different options to add one month to the current date.

2.1. Using Calendar Class

For versions earlier than Java 8, we can use Calendar to handle temporal data. This class offers a set of methods that we can use to manipulate date and time.

@Test void givenCalendarDate_whenAddingOneMonth_thenDateIsChangedCorrectly() < Calendar calendar = Calendar.getInstance(); // Dummy current date calendar.set(2023, Calendar.APRIL, 20); // add one month calendar.add(Calendar.MONTH, 1); assertEquals(Calendar.MAY, calendar.get(Calendar.MONTH)); assertEquals(20, calendar.get(Calendar.DAY_OF_MONTH)); assertEquals(2023, calendar.get(Calendar.YEAR)); >

As we can see, we used the add() method to add exactly one month to the given date. Calendar.MONTH is the constant that denotes months.

2.2. Using Date Class

Date class is another option to consider if we want to change the month of a particular date. However, the drawback of this choice is that this class is deprecated.

Let’s see the use of Date using a test case:

@SuppressWarnings("deprecation") @Test void givenDate_whenAddingOneMonth_thenDateIsChangedCorrectly()

As we can see above, the Date class provides the getMonth() method which returns a number representing the month. Furthermore, we added 1 to the returned number. Then, we called setMonth() to update the Date object with the new month.

Notably, it’s always recommended to use the new Date/Time API of Java 8 instead of the old one.

2.3. Using LocalDate Class

Similarly, we can use the LocalDate class introduced in Java 8. This class offers a straightforward and concise way to add months to a specific date through the plusMonths() method:

@Test void givenJavaLocalDate_whenAddingOneMonth_thenDateIsChangedCorrectly()

Unsurprisingly, the test case passes with success.

3. Using Joda-Time

If Java 8 isn’t an option, we can opt for the Joda-Time library to achieve the same objective.

First, we need to add its dependency to the pom.xml file:

Joda-Time provides its own version of the LocalDate class. So, let’s see how we can use it to add one month:

@Test void givenJodaTimeLocalDate_whenAddingOneMonth_thenDateIsChangedCorrectly()

As we can see, LocalDate also comes with the same method plusMonths(). As the name indicates, it allows us to add a certain number of months, which is 1 in our case.

4. Using Apache Commons Lang3

Alternatively, we can use the Apache Commons Lang3 library. As usual, to get started using this library, we first need to add the Maven dependency :

 org.apache.commons commons-lang3 3.12.0 

Typically, Apache Commons Lang3 provides the DateUtils utility class to perform a bunch of date operations.

Let’s see how to use it using a practical example:

@Test void givenApacheCommonsLangDateUtils_whenAddingOneMonth_thenDateIsChangedCorrectly()

In a nutshell, we used the addMonths() method to increment the specified month by one. An important point to note here is that this method returns a new Date object. The original object remains unchanged.

5. Conclusion

In this short article, we explored different ways of adding one month to the current date in Java.

First, we saw how to do this using core Java classes. Then, we learned how to achieve the same using third-party libraries such as Joda Time and Apache Commons Lang3.

As always, the code samples used in this article can be found over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Java 8 LocalDate plusMonths() Method

Java plusMonths() method is used to add months to a date. It belongs to LocalDate class. This method is included in Java 8 version with DataTime API. We can use it to increase a date by adding months.

For example, 2020-01-01 plus one month will result in 2020-02-01.

We must import java.time package to use this class.

In this topic, we will learn how to add months to a date with examples. Syntax of the method is given below.

Syntax

public LocalDate plusMonths (long monthsToAdd)

This method belongs to Java 8 LocalDate class which is stored into java.time package and method description is given below..

Parameters:

monthsToAdd — It represents number of months to add. It may be positive or negative.

Returns:

The plusMonths() method returns a copy of the LocalDate after adding months.

Exception:

This method throws an exception: DateTimeException if the result exceeds the supported date range.

Example: How to Add Months to a Date in java

Lets take an example in which we are adding months to a date by using plusMonths() method. We can see after adding months date is increased.

import java.time.LocalDate; //Example to Add months to a Date public class Demo < public static void main(String[] args)< // Take a date LocalDate date = LocalDate.parse("2020-05-03"); // Displaying date System.out.println("Date : "+date); // Add 2 months to the date LocalDate newDate = date.plusMonths(2); System.out.println("New Date : "+newDate); >>

Date : 2020-05-03
New Date : 2020-07-03

How to Add a Month to Current Date in Java

Let’s take another example in which we are adding a month to the current date. We are using plusMonths() method to add months to a date. Notice, after adding one month to a date, it increased.

The now() method is used to get the current localdate.

import java.time.LocalDate; //Example to Add months to a Date public class Demo < public static void main(String[] args)< // Take a date LocalDate date = LocalDate.now(); // Displaying date System.out.println("Date : "+date); // Add 1 month to the date LocalDate newDate = date.plusMonths(1); System.out.println("New Date : "+newDate); >>

Date : 2020-05-03
New Date : 2020-06-03

Negative Integer Argument

We can use plusMonths() method to subtract months from a date as well. If we pass negative value as an argument then it will subtract months from the date.

This method works completly opposite if argument is a negative integer. See the following example.

import java.time.LocalDate; //Example to Subtract months to a Date public class Demo < public static void main(String[] args)< // Take a date LocalDate date = LocalDate.parse("2020-05-03"); // Displaying date System.out.println("Date : "+date); // Subtract 2 months from a date LocalDate newDate = date.plusMonths(-2); // negative integer System.out.println("New Date : "+newDate); >>

Date : 2020-05-03
New Date : 2020-03-03

Conclusion

Well, in this topic, we have learned To add number of months to a date which is created by using LocalDate class. This method returns a copy of date after adding the months, we used several examples to explain use of plusMonths() method..

If we missed something, you can suggest us at — info.javaexercise@gmail.com

Источник

Читайте также:  Riot zombie сервера css
Оцените статью