2014-02-27 110 views
-5

我需要得到當前的月份,從此到過去1年的月份沒有要生成報告。如何在java中獲得當前年份和上一年的月份?

例如:如果今天是2月,那麼從02 - 2014年到03-2013我需要生成。

02 - 2014 
01 - 2014 
12 - 2013 
11 - 2013 
. 
. 
. 
03 - 2013 

我需要生成這個。誰可以幫我這個事?

+2

爲什麼標記爲SQL?還有什麼你忘了提及或標籤錯誤? –

+3

另外,它通常是一種很好的形式,可以先去編碼它。 –

+3

'我需要產生這個'什麼阻止你?你還沒有問過任何問題。 – Pshemo

回答

0

在這裏,您將使用第三方開源Joda-Time框架的示例。 Joda-Time是一種流行的替代品,可以替代過時的Java java.util.Date &.Calendar類。

DateTime now = DateTime.now(); // Current date-time using JVM's default time zone. 
DateTime pastDate = null; 
for (int i = 0; i < 12; i++) { 
    pastDate = now.minusMonths(i); 
    String monthNumberAsString = String.format("%02d", pastDate.getMonthOfYear()); // Pad leading zero if need be. 
    System.out.println(monthNumberAsString + " - " + pastDate.getYear()); 
} 

生成

02 - 2014 
01 - 2014 
12 - 2013 
11 - 2013 
10 - 2013 
09 - 2013 
08 - 2013 
07 - 2013 
06 - 2013 
05 - 2013 
04 - 2013 
03 - 2013 

Java 8帶來新java.time package以取代舊java.util.Date/Calendar類。這些新課程的靈感來自Joda-Time,並由JSR 310定義。

+2

如果你打算用非標準的API(jodatime)來回答,至少在你的回答中提到這一點很好。 – ryvantage

+2

也許可以解釋爲什麼要使用第三方API而不是標準API(它提供了完全相同的功能)。 – jarnbjo

2

你可能想看看add方法日曆例如:

import java.text.SimpleDateFormat; 
import java.util.Calendar; 
import java.util.GregorianCalendar; 


public class CalendarExample { 

    public static void main(String[] args) { 
    SimpleDateFormat sdf = new SimpleDateFormat("MM - yyyy"); 
    Calendar calendar = new GregorianCalendar(); 
    System.out.println(sdf.format(calendar.getTime())); 

    for (int i = 0; i < 11; i++) { 
     calendar.add(Calendar.MONTH, -1); 
     System.out.println(sdf.format(calendar.getTime())); 
    } 

    } 
} 

產生:

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

如果你想要的是1年回覆日期,你可以使用:

public static void main(String[] args){ 
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 
    System.out.println(df.format(getPastDate())); 

} 

public static Date getPastDate(){ 
    Calendar calendar = Calendar.getInstance(); 
    calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR)-1); 
    calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)+1); 
    System.out.println(calendar.getTime()); 
    return calendar.getTime(); 
} 
-2
import java.util.*; 
class dt 
{ 
    Date d; 
    String mon;   
    dt() 
    { d= new Date(); 
     mon = ""+(d.getMonth()+1)+""; 
     System.out.println(" mon is "+);   
    } 
    public static void main(String[]avi) 
    {  new dt(); } 
} 

此代碼將返回當月

像...使用方法d.getYear()來獲得本年度

注:週一= 「」 +(d.getMonth()+ 1)+ 「」; 在這個我已經添加了1個月,因爲此方法返回0 - >對於1,>對於二等...

相關問題