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.
getTime(); Date sumDate = new Date(sum); The code uses the . getTime() method that returns the number of milliseconds since the epoch.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With