tags:

views:

404

answers:

4

I have a String in format yyyyMMdd. Is there a simple way to get a String with previous date in the same format? Thanks

+4  A: 

use SimpleDateFormat to parse the String to Date, then subtract one day. after that convert the date to String again.

Wiliam Witter
+5  A: 

It's much harder than it should be in Java without library support.

You can parse the given String into a Date object using an instance of the SimpleDateFormat class.

Then you can use Calendar's add() to subtract one day.

Then you can use SimpleDateFormat's format() to get the formatted date as a String.

The Joda Time library a much easier API.

Brabster
+3  A: 

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();
        }
    }
}
William Brendel
Most of the code inside the try block doesn't even throw ParseException. You should limit its scope.
Steve Kuo
Makes for a slightly simpler example. That's the only reason I did it that way...
William Brendel
Thanks!The example was useful.I've used: DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); Calendar cal = new GregorianCalendar();.. cal.setTime(dateFormat.parse(strDate)); cal.add(Calendar.DAY_OF_YEAR, -1); strDate= dateFormat.format( cal.getTime() );
Serg
Glad I could help!
William Brendel
Any specific reason you didn't use `Calendar.getInstance()`? To be on the safe side I would call `calendar.clear()` directly after constructing/getting it to avoid timezone clashes.
BalusC
this methods seems to encounter problems with the input "00010101".
vkraemer
@BalusC I modified the example to use `getInstance()`. I just wasn't aware that method existed in `Calendar`, and I had always just used `GregorianCalendar`. Also, according to the documentation, `getInstance()` will return an instance using the default timezone and locale, so I'm not sure what the benefit of calling `clear()` would be in this case. Am I missing something?
William Brendel
@vkraemer I think that qualifies as an edge case. In general, I think this solution works well :-)
William Brendel
@William: you're right wrt timezone, this is here indeed not the case.
BalusC
If this is going to get called in a loop, you probably want to think about changing the scope of the objects that get created... like the Calendar object.
vkraemer
+1  A: 

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.

vkraemer
You'll only run into problems when DST disturbs. Your code may then return the same day.
BalusC