如何获得当月,上个月和两个月前

Dan*_*ica -4 java

我需要一个返回三个字符串的函数:

  1. 第一个字符串将包含当前月份和当前年份.
  2. 第二个字符串将包含上个月和当前年份.
  3. 第三个字符串将包含两个月前和当前年份.

当然,如果当前月份是1月,这也应该有用.

所以现在,结果应该是:

  • 2015年9月
  • 2015年8月
  • 2015年7月

Phy*_*sis 10

Java 8版本(使用java.time.YearMonth该类)就在这里.

YearMonth thisMonth    = YearMonth.now();
YearMonth lastMonth    = thisMonth.minusMonths(1);
YearMonth twoMonthsAgo = thisMonth.minusMonths(2);

DateTimeFormatter monthYearFormatter = DateTimeFormatter.ofPattern("MMMM yyyy");

System.out.printf("Today: %s\n", thisMonth.format(monthYearFormatter));
System.out.printf("Last Month: %s\n", lastMonth.format(monthYearFormatter));
System.out.printf("Two Months Ago: %s\n", twoMonthsAgo.format(monthYearFormatter));
Run Code Online (Sandbox Code Playgroud)

这打印出以下内容:

今天:2015年9月

上个月:2015年8月

两个月前:2015年7月


Dav*_*INO 6

Calendar c = new GregorianCalendar();
c.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("MMMM YYYY");
System.out.println(sdf.format(c.getTime()));   // NOW
c.add(Calendar.MONTH, -1);
System.out.println(sdf.format(c.getTime()));   // One month ago
c.add(Calendar.MONTH, -1);
System.out.println(sdf.format(c.getTime()));   // Two month ago
Run Code Online (Sandbox Code Playgroud)