Varathan Swaminath
Varathan Swaminath

Reputation: 98

Print past 6 month names from current month in Java

I need to print the past 6 month name from current month.

For example, when run in April 2016, I need to print: nov(2015), dec(2015), jan(2016), feb(2016), march(2016), april(2016)

Format formatter = new SimpleDateFormat("MMMM YYYY");
Calendar c = Calendar.getInstance();

String[] thisAndLastFiveMonths = new String[6];
for (int i = 0; i < thisAndLastFiveMonths.length; i++) {
    thisAndLastFiveMonths[i] = formatter.format(c.getTime());
    c.add(Calendar.MONTH, -1);
    System.out.println(c);

Upvotes: 1

Views: 1064

Answers (1)

Tunaki
Tunaki

Reputation: 137084

Using the Java Time API, you can construct a YearMonth object representing the current year-month and call minusMonths to subtract a number of months.

Then, you can get the textual representation of the month name with Month.getDisplayName(style, locale). The given TextStyle is used to style the output; you can use SHORT for your case:

Short text, typically an abbreviation. For example, day-of-week Monday might output "Mon".

public static void main(String[] args) {
    for (int i = 5; i >= 0; i--) {
        YearMonth date = YearMonth.now().minusMonths(i);
        String monthName = date.getMonth().getDisplayName(TextStyle.SHORT, Locale.ENGLISH);
        System.out.println(monthName + "(" + date.getYear() + ")");
    }
}

prints, when run in April 2016:

Nov(2015)
Dec(2015)
Jan(2016)
Feb(2016)
Mar(2016)
Apr(2016)

Upvotes: 8

Related Questions