2014-02-27 111 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,>对于二等...

相关问题