2014-10-20 67 views
1

我想從沒有任何庫的整數中減去幾個月。Java減去沒有庫的月份

的問題是,當我減1個月,從第一個月:0(1月)應該是12(月),但是這將是-1 ..

這是我的代碼添加

int currentMonthInt = Integer.parseInt(currentMonth) - 1; 
    int currentYearInt = Integer.parseInt(currentYear); 

    // show today month 
    if (dateposition == 0){ 
     showListView(currentMonth, currentYear, db); 
    } 

    // show next month 
    for (int i = 1; i <=200; i++){ 
     if (dateposition == i){ 
      int month = currentMonthInt + i; 
      int year = currentYearInt + (month/12); 
      month = (month % 12)+1; 

      String monthString = String.format("%02d", month); 
      String yearString = String.valueOf(year); 
      showListView(monthString, yearString, db); 
     } 
    } 

,這是我減去代碼:(但忽略了最低工作)

for (int i = -200; i < 0; i++){ 
      //This is not correct! 
      //int month = currentMonthInt + i; 
      //int year = currentYearInt + (month/12); 
      //month = (month % 12)+1; 

      String monthString = String.format("%02d", month); 
      String yearString = String.valueOf(year); 
      showListView(monthString, yearString, db); 
    } 

PS dateposition是其+1其下個月一個月如果0的今天個月,一年,如果位置等,如果它-1的分組月

+1

嘗試使用[喬達](http://www.joda.org/joda-time/)庫 – 2014-10-20 17:04:34

+0

碼減去'月=(每月12%)+1;'你確定其正確的? ,如果你有月0,即使在這種情況下,以上公式只會返回你一個。 – 2014-10-20 17:05:41

+0

當'a'爲負數時'a%b'可能會給出負數。 – Henry 2014-10-20 17:06:02

回答

0

好吧,我寫了,我測試它的工作!

for (int i = -200; i < 0; i++){ 
     if (dateposition == i){ 
      int month = currentMonthInt + i; 
      int year = currentYearInt + (month/12); 

      if (month >= 0){ 
       month = (month % 12)+1; 
      } else { 
       int c1 = Math.abs(month/12) + 1; 
       month += (12 * c1); 
      } 

      String monthString = String.format("%02d", month); 
      String yearString = String.valueOf(year); 
      showListView(monthString, yearString, db); 
     } 
    } 
+0

它在這段代碼中有一些問題。 – 2014-11-01 22:42:18

-2

使用Joda library

public void test() { 
    LocalDate fromDate = LocalDate.now(); 
    System.out.println(fromDate); 
    LocalDate newYear = fromDate; 
    for (int i = 0; i < 10; i++) { 
     newYear = newYear.minusMonths(1); 
     System.out.print(newYear + ", "); 
    } 
    System.out.println("\n-------"); 
    newYear = fromDate; 
    for (int i = 0; i < 10; i++) { 
     newYear = newYear.plusMonths(1); 
     System.out.print(newYear + ", "); 
    } 
} 

輸出:

2014-10-20 
2014-09-20, 2014-08-20, 2014-07-20, 2014-06-20, 2014-05-20, 2014-04-20, 2014-03-20, 2014-02-20, 2014-01-20, 2013-12-20, 
------- 
2014-11-20, 2014-12-20, 2015-01-20, 2015-02-20, 2015-03-20, 2015-04-20, 2015-05-20, 2015-06-20, 2015-07-20, 2015-08-20, 
+0

謝謝,但我不想使用庫。我想使用整數... – 2014-10-20 17:19:15