java取当前时间的前一天/后一天

来源:互联网 发布:js根据固定格式化金额 编辑:程序博客网 时间:2024/05/16 07:31

/**
  * 用于返回指定日期的下一天的日期
  *
  * @param appDate
  *            指定日期
  * @return 指定日期的下一天的日期
  */
 public static String getNextDay(String appDate) {
  return getFutureDay(appDate, "yyyy-MM-dd", 1);
 }

 /**
  * 用于返回指定日期增加指定天数的日期
  *
  * @param appDate
  *            指定日期
  * @param days
  *            指定天数
  * @return 指定日期增加指定天数的日期
  *
  */
 public static String getFutureDay(String appDate, int days) {
  return getFutureDay(appDate, "yyyy-MM-dd", days);
 }

 /**
  * 用于返回指定日期格式的日期增加指定天数的日期
  *
  * @param appDate
  *            指定日期
  * @param format
  *            指定日期格式
  * @param days
  *            指定天数
  * @return 指定日期格式的日期增加指定天数的日期
  */
 public static String getFutureDay(String appDate, String format, int days) {
  String future = "";
  try {
   Calendar calendar = GregorianCalendar.getInstance();
   SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
   Date date = simpleDateFormat.parse(appDate);
   calendar.setTime(date);
   calendar.add(Calendar.DATE, days);
   date = calendar.getTime();
   future = simpleDateFormat.format(date);
  } catch (Exception e) {

  }

  return future;
 }

 

 

 /*
 *主函数测试
 */
 public static void main(String arg[])
 {


  CalendarUtil caleutil = new CalendarUtil();
  Date d1=new Date();
  long myTime = (d1.getTime()/1000)-60*60*24;
  d1.setTime(myTime*1000);
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
  format.format(d1);
  System.out.println("取得昨天时间:  "+format.format(d1));

-------------------------------------------------------------------------------------------------
  Date d2=new Date();
  SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
  d2.setTime(System.currentTimeMillis());
  caleutil.getNextDay(format.format(d2));
  System.out.println("取得明天时间:  "+caleutil.getNextDay(format.format(d2)));

 

 }