2010-11-07 34 views
0
import java.util.*;  
import java.text.*; 

public class GetPreviousAndNextDate 
{ 
    public static void main(String[] args) 
    {  
     int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;  
     Date date = new Date();  
     SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy"); 
     String prevDate = dateFormat.format(date.getTime() - MILLIS_IN_DAY); 
     String currDate = dateFormat.format(date.getTime()); 
     String nextDate = dateFormat.format(date.getTime() + MILLIS_IN_DAY); 

     System.out.println("Previous date: " + prevDate); 
     System.out.println("Currnent date: " + currDate); 
     System.out.println("Next date: " + nextDate); 
    } 
} 

我有這個錯誤方法錯誤的SimpleDateFormat

(Error(9,32): method format(long) not found in class java.text.SimpleDateFormat) 

回答

0

這些線路使用不存在的方法:

String prevDate = dateFormat.format(date.getTime() - MILLIS_IN_DAY); 

String currDate = dateFormat.format(date.getTime()); 

String nextDate = dateFormat.format(date.getTime() + MILLIS_IN_DAY); 

方法format接受Date對象作爲參數。

試試這個:

String prevDate = dateFormat.format(new Date(date.getTime() - MILLIS_IN_DAY)); 
2

你的代碼的邏輯是錯誤的。結果將在夏令時開關周圍停留一個小時,因爲這涉及23或25小時的日子。

對於日期arithmethic,你應該總是使用日曆類:

Calendar cal = Calendar.getInstance(); 
    cal.add(Calendar.DAY_OF_MONTH, -1); 
    String prevDate = dateFormat.format(cal.getTime()); 
    cal.add(Calendar.DAY_OF_MONTH, 2); 
    String nextDate = dateFormat.format(cal.getTime()); 

(注意:Calendar.getTime()返回Date對象,從而修正了錯誤類型爲好)