java

java获取日期(过去某一天、将来某一天)

2019-07-18  本文已影响0人  岁月静好忄

java获取过去第几天的日期和获取未来/将来第几天日期
带有英文日期格式化

   /** 
    * 获取过去第几天的日期 
    * @param past 
    * @return 
    */  
   public static String getPastDate(int past) {  
       Calendar calendar = Calendar.getInstance();  
       calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);  
       Date today = calendar.getTime();  
       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
       String result = format.format(today);  
       Log.e(null, result);  
       return result;  
   }  
  
   /** 
    * 获取未来 第 past 天的日期 
    * @param past 
    * @return 
    */  
   public static String getFetureDate(int past) {  
       Calendar calendar = Calendar.getInstance();  
       calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);  
       Date today = calendar.getTime();  
       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
       String result = format.format(today);  
       Log.e(null, result);  
       return result;  
   }

带有英文日期字符串格式化


String dateStr = "18:58:43 Dec 11 2019";
try
{
    Date date = new SimpleDateFormat("HH:mm:ss MMMM dd yyyy", Locale.ENGLISH).parse(dateStr);
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    String result = format.format(date);  
    System.out.println(result);
} catch (ParseException e)
{
    e.printStackTrace();
}

上面输出结果:2019-12-11 18:58:43

上一篇下一篇

猜你喜欢

热点阅读