2012-01-20 38 views
-2

如果當前日期以字符串形式給出,如何查找以前的日期?下面給出我的代碼。有沒有更短的解決方案?如果當前日期以字符串形式給出,如何查找以前的日期?

private static String previousDay(String date) { 
     String[] ymd = date.split("-"); 
     int year = Integer.parseInt(ymd[0]); 
     int month = Integer.parseInt(ymd[1]); 
     int day = Integer.parseInt(ymd[2]); 
     String newDate = ""; 
     if (day > 1 & month > 1) 
      newDate = year+"-"+month+"-"+(day-1); 
     else if (day == 1 & month > 1) { 
      Calendar calendar = new GregorianCalendar(year,month-1, 1); 
      int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); 
      newDate = year+"-"+(month-1)+"-"+daysInMonth; 
     } else if (day == 1 & month == 1) { 
      Calendar calendar = new GregorianCalendar(year,12, 1); 
      int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); 
      newDate = year+"-"+12+"-"+daysInMonth; 
     } 
     return newDate; 
    } 
+1

嗯,我會使用SimpleDateFormat的字符串恢復到java.util.Date對象,然後使用它。很快就會發布代碼。 – BigMike

+3

[如何在java中獲取上一個日期](http://stackoverflow.com/questions/2458049/how-to-get-previous-date-in-java) – dogbane

回答

3

您需要將字符串轉換爲日期才能進行日期計算。您可以使用日曆查找前一天。在我的假設中,你的日期格式是yyyy-MM-dd。

String input = "2009-09-30"; 
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
Date myDate = dateFormat.parse(input); 
Calendar cal1 = Calendar.getInstance(); 
cal1.setTime(myDate); 
cal1.add(Calendar.DAY_OF_YEAR, -1); 
Date previousDate = cal1.getTime(); 
0
// dccTimeStamp is "20120122121212" 
String dccTimeStamp is "20120122121212" 
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); 
Date dcc = sdf.parse(dccTimeStamp); 
log.debug("Dcc Date is " + dcc.toString()); 

從這一點上,你可以使用日期(或日曆)實用程序和執行你所需要的時間操作。

1
Date currentDate= new Date(); 

Calendar calendar = Calendar.getInstance(); 
calendar.setTime(currentDate); 
calendar.add(Calendar.DAY_OF_YEAR, -1); 

Date previousDate = calendar.getTime(); 
相關問題