how-to

Working with Date

How to calc with date

For this example you need to use:

import java.util.*;

When you need to do some aritmethic operation with java.util.Date class, use class java.util.Calendar.

Calendar cal = Calendar.getInstance();

java.util.Date d = cal.getTime();

/* -- + one week in month */>

cal.setTime( d );

System.out.println( "+1 week" );
System.out.println( cal.getTime() );
cal.add( Calendar.DAY_OF_WEEK_IN_MONTH, 1 );
System.out.println( cal.getTime() );

System.out.println();

/* -- + 5000 minutes */

cal.setTime( d );

System.out.println( "+5000 minutes" );
System.out.println( cal.getTime() );
cal.add( Calendar.MINUTE, 5000 );
System.out.println( cal.getTime() );

System.out.println();

/* -- + 3 days */>

cal.setTime( d );

System.out.println( "+3 days" );
System.out.println( cal.getTime() );
cal.add( Calendar.DAY_OF_MONTH, 3 );
System.out.println( cal.getTime() );

System.out.println();

/* -- - 15 months */

cal.setTime( d );

System.out.println( "-15 months" );
System.out.println( cal.getTime() );
cal.add( Calendar.MONTH, -15 );
System.out.println( cal.getTime() );

System.out.println();

/* -- result */

java.util.Date dNew = cal.getTime();

System.out.println( dNew );
The output could be:
+1 week
Fri Oct 12 14:56:28 CEST 2012
Fri Oct 19 14:56:28 CEST 2012

+5000 minutes
Fri Oct 12 14:56:28 CEST 2012
Tue Oct 16 02:16:28 CEST 2012

+3 days
Fri Oct 12 14:56:28 CEST 2012
Mon Oct 15 14:56:28 CEST 2012

-15 months
Fri Oct 12 14:56:28 CEST 2012
Tue Jul 12 14:56:28 CEST 2011

Tue Jul 12 14:56:28 CEST 2011