javadate

Identifying the season from the Date using Java


I've had nothing but good luck from SO, so why not try again?

I have an application that needs to show a different image based on the season of the year (spring, summer, winter, fall). I have very specific start and end dates for these seasons.

What I would like from you geniuses is a method called GetSeason that takes a date as input and returns a String value of Spring, Summer, Winter or Fall. Here are the date ranges and their associated seasons:

Spring:3/1-4/30
Summer:5/1-8/31
Fall:9/1-10/31
Winter: 11/1-2/28

Can someone provide a working method to return the proper season? Thanks everyone!


Solution

  • Seems like just checking the month would do:

    private static final String seasons[] = {
      "Winter", "Winter", "Spring", "Spring", "Summer", "Summer", 
      "Summer", "Summer", "Fall", "Fall", "Winter", "Winter"
    };
    public String getSeason( Date date ) {
       return seasons[ date.getMonth() ];
    }
    
    // As stated above, getMonth() is deprecated, but if you start with a Date, 
    // you'd have to convert to Calendar before continuing with new Java, 
    // and that's not fast.