Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addition and Subtraction of Dates in Java

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.

like image 661
John Woo Avatar asked Apr 12 '12 06:04

John Woo


People also ask

How do you sum dates in Java?

getTime(); Date sumDate = new Date(sum); The code uses the . getTime() method that returns the number of milliseconds since the epoch.

How do I combine two dates in Java?

this is the origin of the two variables : @Temporal(value = TemporalType. DATE) @Future @DateTimeFormat(pattern = "dd/MM/YY") @Column(name = "dateDebut", nullable = true) private Date date; @Temporal(TemporalType.

How do you subtract two date strings in Java?

Parse both start_date and end_date from a string to produce the date, this can be done by using parse() method of the simpleDateFormat class. Find the time difference between two dates in millisecondes by using the method getTime() in Java as d2. getTime() – d1.


2 Answers

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
}
like image 194
Betlista Avatar answered Oct 13 '22 00:10

Betlista


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.

like image 32
dty Avatar answered Oct 12 '22 22:10

dty