How to get previous date in java

I would rewrite these answers a bit.

You can use

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        // Get a Date object from the date string
        Date myDate = dateFormat.parse(dateString);

        // this calculation may skip a day (Standard-to-Daylight switch)...
        //oneDayBefore = new Date(myDate.getTime() - (24 * 3600000));

        // if the Date->time xform always places the time as YYYYMMDD 00:00:00
        //   this will be safer.
        oneDayBefore = new Date(myDate.getTime() - 2);

        String result = dateFormat.format(oneDayBefore);

To get the same results as those that are being computed by using Calendar.


Here is how to do it without Joda Time:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {

    public static String previousDateString(String dateString) 
            throws ParseException {
        // Create a date formatter using your format string
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        // Parse the given date string into a Date object.
        // Note: This can throw a ParseException.
        Date myDate = dateFormat.parse(dateString);

        // Use the Calendar class to subtract one day
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(myDate);
        calendar.add(Calendar.DAY_OF_YEAR, -1);

        // Use the date formatter to produce a formatted date string
        Date previousDate = calendar.getTime();
        String result = dateFormat.format(previousDate);

        return result;
    }

    public static void main(String[] args) {
        String dateString = "20100316";

        try {
            // This will print 20100315
            System.out.println(previousDateString(dateString));
        } catch (ParseException e) {
            System.out.println("Invalid date string");
            e.printStackTrace();
        }
    }
}

Tags:

Java

Date