2009-09-13 192 views
9

我有一個程序需要在2009年1月1日開始,當我開始新的一天時,我的程序將在第二天顯示。 這是我到目前爲止有:將日期添加到日期

GregorianCalendar startDate = new GregorianCalendar(2009, Calendar.JANUARY, 1); 
SimpleDateFormat sdf = new SimpleDateFormat("d/M/yyyy"); 
public void setStart() 
{ 
    startDate.setLenient(false); 
    System.out.println(sdf.format(startDate.getTime())); 
} 

public void today() 
{ 
    newDay = startDate.add(5, 1); 
    System.out.println(newDay); 
//I want to add a day to the start day and when I start another new day, I want to add another day to that. 
} 

我收到錯誤發現無效,但預計INT,在「newDay = startDate.add(5,1);」 我該怎麼辦?

+3

幾個小時內約三個問題。也許是時候先看看API了。 – camickr 2009-09-13 05:22:34

回答

18

Calendar對象有一個add方法,它允許添加或減去指定字段的值。

例如,

Calendar c = new GregorianCalendar(2009, Calendar.JANUARY, 1); 
c.add(Calendar.DAY_OF_MONTH, 1); 

用於指定字段中的常數可以在Calendar類的「字段摘要」中找到。

僅供將來參考,The Java API Specification包含大量關於如何使用屬於Java API一部分的類的有用信息。


更新:

我正在錯誤發現空隙但 預期INT,在 'newDay = startDate.add(5,1);'我應該怎麼做 ?

add方法不返回任何東西,因此,嘗試指派調用Calendar.add是無效的結果。

編譯器錯誤表明正在嘗試將void分配給類型爲int的變量。這是無效的,因爲不能將「無」分配給變量int

只是一個猜測,但也許這可能是什麼努力來實現:

// Get a calendar which is set to a specified date. 
Calendar calendar = new GregorianCalendar(2009, Calendar.JANUARY, 1); 

// Get the current date representation of the calendar. 
Date startDate = calendar.getTime(); 

// Increment the calendar's date by 1 day. 
calendar.add(Calendar.DAY_OF_MONTH, 1); 

// Get the current date representation of the calendar. 
Date endDate = calendar.getTime(); 

System.out.println(startDate); 
System.out.println(endDate); 

輸出:

Thu Jan 01 00:00:00 PST 2009 
Fri Jan 02 00:00:00 PST 2009 

有什麼需要考慮的是什麼Calendar實際上是。

A Calendar不代表日期。它是日曆的表示,以及它當前指向的位置。爲了得到此時日曆所指的位置,應使用getTime方法從Calendar獲得Date

+0

我正打算輸入API的鏈接! – vpram86 2009-09-13 05:18:57

1

如果你可以擺動它的需求明智的,移動所有的日期/時間需要JODA,這是一個更好的圖書館,與幾乎所有東西都是不變的額外獎金,這意味着多線程免費進來。