java 已知一个Date(),获取前一天和后一天

  1. import java.text.ParseException;  
  2. import java.text.SimpleDateFormat;  
  3. import java.util.Calendar;  
  4. import java.util.Date;  
  5.   
  6. public class DateUtil {  
  7.       
  8.     public static void main(String[] args) {  
  9.         Date date = new Date();  
  10.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
  11.         String specifiedDay = sdf.format(date);  
  12.         System.out.println(getSpecifiedDayBefore(specifiedDay));  
  13.         System.out.println(getSpecifiedDayAfter(specifiedDay));  
  14.     }  
  15.       
  16.     /** 
  17.      * 获得指定日期的前一天 
  18.      *  
  19.      * @param specifiedDay 
  20.      * @return 
  21.      * @throws Exception 
  22.      */  
  23.     public static String getSpecifiedDayBefore(String specifiedDay) {//可以用new Date().toLocalString()传递参数  
  24.         Calendar c = Calendar.getInstance();  
  25.         Date date = null;  
  26.         try {  
  27.             date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);  
  28.         } catch (ParseException e) {  
  29.             e.printStackTrace();  
  30.         }  
  31.         c.setTime(date);  
  32.         int day = c.get(Calendar.DATE);  
  33.         c.set(Calendar.DATE, day - 1);  
  34.   
  35.         String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c  
  36.                 .getTime());  
  37.         return dayBefore;  
  38.     }  
  39.   
  40.     /** 
  41.      * 获得指定日期的后一天 
  42.      *  
  43.      * @param specifiedDay 
  44.      * @return 
  45.      */  
  46.     public static String getSpecifiedDayAfter(String specifiedDay) {  
  47.         Calendar c = Calendar.getInstance();  
  48.         Date date = null;  
  49.         try {  
  50.             date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);  
  51.         } catch (ParseException e) {  
  52.             e.printStackTrace();  
  53.         }  
  54.         c.setTime(date);  
  55.         int day = c.get(Calendar.DATE);  
  56.         c.set(Calendar.DATE, day + 1);  
  57.   
  58.         String dayAfter = new SimpleDateFormat("yyyy-MM-dd")  
  59.                 .format(c.getTime());  
  60.         return dayAfter;  
  61.     }  
  62. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值