Friday, August 28, 2009

Retrieve Previous, Current and Next Date using Java

Using Java Class "Date" you can get date using Date d = new Date();
Java Provies class named SimpleDateFormat which allows to format date to specific DateFormat.

Using Following program You can  :

  1. Retrieve Current Date in Java
  2. Retrieve Previous Date in Java
  3. Retrieve Next Date in Java
Java Program to retrieve Current Date , Previous Date and Next Day :


package com.anuj.basic;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author Anuj Patel
 */
public class DateOperations {

    public static void main(String[] args) {
        int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;

        Date date = new Date();

        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");

        String prevDate = dateFormat.format(date.getTime() - MILLIS_IN_DAY);
        String currDate = dateFormat.format(date.getTime());
        String nextDate = dateFormat.format(date.getTime() + MILLIS_IN_DAY);

        System.out.println("Previous date: " + prevDate);
        System.out.println("Currnent date: " + currDate);
        System.out.println("Next date: " + nextDate);
    }
}
Output :
Previous date: 03/11/12
Currnent date: 04/11/12
Next date: 05/11/12
BUILD SUCCESSFUL (total time: 13 seconds)

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/