I have a String Object in format yyyyMMdd.Is there a simple way to get a String with previous date in the same format? Thanks
Use LocalDate 's plusDays() and minusDays() method to get the next day and previous day, by adding and subtracting 1 from today.
Date date = DateUtils. addDays(new Date(), -1); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf. format(date); will do the trick.
The getTime() method of Java Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GTM which is represented by Date object.
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With