import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public final class Utils { /** * get any time which you want before or after today. * @param year by number years(before or after this year) default:0 * @param month by number months(before or after this month)default:0,no change * @param day by number day(before or after this day)default:0,no change * @return */ public static Date getCountDate(int year, int month, int day){ Calendar cal = Calendar.getInstance (); cal.add (Calendar.YEAR, year); cal.add (Calendar.MONDAY, month); cal.add (Calendar.DATE, day); return cal.getTime (); } public static String dateToString (Date date) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String temp = format.format (date); return temp; } public static void main(String[] args){ Date today = Utils.getCountDate (0, 0, 0); Date oneYearBefore = Utils.getCountDate (-1, 0, 0); Date oneMonthBefore = Utils.getCountDate (0, -1, 0); Date oneDayBefore = Utils.getCountDate (0, 0, -1); Date oneYearAfter = Utils.getCountDate (1, 0, 0); Date oneMonthAfter = Utils.getCountDate (0, 1, 0); Date oneDayAfter = Utils.getCountDate (0, 0, 1); System.out.println (today + "\t" + Utils.dateToString (today)); System.out.println (oneYearBefore + "\t" + Utils.dateToString (oneYearBefore)); System.out.println (oneMonthBefore + "\t" + Utils.dateToString (oneMonthBefore)); System.out.println (oneDayBefore + "\t" + Utils.dateToString (oneDayBefore)); System.out.println (oneYearAfter + "\t" + Utils.dateToString (oneYearAfter)); System.out.println (oneMonthAfter + "\t" + Utils.dateToString (oneMonthAfter)); System.out.println (oneDayAfter + "\t" + Utils.dateToString (oneDayAfter)); } }
Result:
Mon Oct 24 16:09:45 CST 2011 2011-10-24
Sun Oct 24 16:09:45 CST 2010 2010-10-24
Sat Sep 24 16:09:45 CST 2011 2011-09-24
Sun Oct 23 16:09:45 CST 2011 2011-10-23
Wed Oct 24 16:09:45 CST 2012 2012-10-24
Thu Nov 24 16:09:45 CST 2011 2011-11-24
Tue Oct 25 16:09:45 CST 2011 2011-10-25