How can we add or subtract date in java? For instance java.sql.Date
and formatted like this: yyyy-MM-dd , how can i Add 5 months from that? I've seen in some tutorial that they are using Calendar
, can we set date on it? Please Help.
Example: 2012-01-01
when added 5 months will become 2012-06-01
.
PS: I'm a.Net Programmer and slowly learning to Java environment.
First of all you have to convert your String
date to java.util.Date
, than you have to use java.util.Calendar
to manipulate dates. It is also possible to do math with millis, but I do not recommend this.
public static void main( final String[] args ) throws ParseException {
final String sdate = "2012-01-01";
final SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd" );
final Date date = df.parse( sdate ); // conversion from String
final java.util.Calendar cal = GregorianCalendar.getInstance();
cal.setTime( date );
cal.add( GregorianCalendar.MONTH, 5 ); // date manipulation
System.out.println( "result: " + df.format( cal.getTime() ) ); // conversion to String
}
Stear clear of the built-in Date class for date math. Take a look at JodaTime, which has a much better API for this kind of thing.
Use Calendar
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 5);
To convert a Date to a Calendar, use:
Date date = your_date_here;
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Then use the calendar arithmetic functions to add/subtract:
cal.add(Calendar.MONTH, 5);
Or, Convert the date to time in milis. Do the math, and convert the millis back to a date.
use CalenderUtils
from google's package GWT.
import com.google.gwt.user.datepicker.client.CalendarUtil;
...
//now
Date d = new Date();
// Now + 2 months
CalendarUtil.addMonthsToDate(d, 2);
Another option is the DateUtils class from the 3rd party Apache Commons library collection. Example:
Date d = DateUtils.parseDate("2012-01-01", "yyyy-MM-dd");
Date d2 = DateUtils.addMonths(d, 5);
System.out.println("Old date + 5 months = " + d2);
There are various ways. One of them could be with joda.time . This does not answer the question by using Calendar but one of the other approach if needed by someone. :D
import java.sql.Date;
import org.joda.time.DateTime;
//
DateTime datetime = new DateTime("2012-01-01");
Date dt = new Date(datetime.plusMonths(5).toDate().getTime());
System.out.println(dt);
// This gives output as 2012-06-01
PS: Happy coding with Java
The accepted answer uses java.util
date-time API and SimpleDateFormat
which was the correct thing to do in 2012. In Mar 2014, the java.util
date-time API and their formatting API, SimpleDateFormat
were supplanted by the modern date-time API . Since then, it is highly recommended to stop using the legacy date-time API.
java.time
, the modern date-time API: You do not need a DateTimeFormatter
for your date string: java.time
API is based on ISO 8601 and therefore you do not need to specify a DateTimeFormatter
to parse a date-time string which is already in ISO 8601 format eg your date string, 2012-01-01
which can be parsed directly into a LocalDate
instance, that contains just date units.
Having parsed the date string into LocalDate
, you can add or subtract different date units eg years, months, days etc. to it.
Demo :
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
class Main {
public static void main(String args[]) {
LocalDate date = LocalDate.parse("2012-01-01");
System.out.println(date);
LocalDate afterFiveMonths = date.plusMonths(5);
LocalDate beforeFiveMonths = date.minusMonths(5);
System.out.println(afterFiveMonths);
System.out.println(beforeFiveMonths);
// Alternatively,
afterFiveMonths = date.plus(5, ChronoUnit.MONTHS);
beforeFiveMonths = date.minus(5, ChronoUnit.MONTHS);
System.out.println(afterFiveMonths);
System.out.println(beforeFiveMonths);
}
}
Output :
2012-01-01
2012-06-01
2011-08-01
2012-06-01
2011-08-01
Learn more about the modern Date-Time API from Trail: Date Time .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.