Sunday 7 April 2013

Increment & Decrements Date In Java

Leave a Comment
import java.text.SimpleDateFormat; 
import java.util.Calendar; 
import java.util.Date;
/**
 *  @author Harit 
 *  */ 

public class IncrementDecrementDate 
{ 
 public static void main(String args[]) 
 { 
  //Using Calendar to increment and decrement days from date in Java 
  Date today = new Date(); 
  System.out.println("Today is " + toddMMyy(today)); 
  Calendar cal = Calendar.getInstance(); 
  
  //adding one day to current date 
  cal.add(Calendar.DAY_OF_MONTH, 1); 
  Date tommrrow = cal.getTime(); 
  System.out.println("Tomorrow will be " + toddMMyy(tommrrow));
  
  //substracting two day from date in Java 
  cal.add(Calendar.DAY_OF_MONTH, -2); 
  Date yesterday = cal.getTime(); 
  System.out.println("Yesterday was " + toddMMyy(cal.getTime())); 
  
  
 } 
 
 public static String toddMMyy(Date day)
 { 
  SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy"); 
  String date = formatter.format(day);
  return date; 
 } 
 
 }




0 comments:

Post a Comment