2

我从 SO 那里得到的只是好运,所以为什么不再试一次呢?

我有一个应用程序需要根据一年中的季节(春季、夏季、冬季、秋季)显示不同的图像。我对这些季节有非常具体的开始和结束日期。

我希望各位天才们提供一种名为 GetSeason 的方法,该方法将日期作为输入并返回 Spring、Summer、Winter 或 Fall 的 String 值。以下是日期范围及其相关季节:

春季:3/1-4/30
夏季:5/1-8/31
秋季:9/1-10/31
冬季:11/1-2/28

有人可以提供一种工作方法来恢复适当的季节吗?谢谢大家!

4

11 回答 11

7

似乎只检查月份就可以了:

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.
于 2008-10-09T22:57:50.727 回答
3

这里有一些很好的答案,但它们已经过时了。java.time 类使这项工作更容易。

java.time

Java 8 及更高版本中内置的java.time类已取代了与最早版本的 Java 捆绑在一起的麻烦的旧类。请参阅Oracle 教程。大部分功能已在 ThreeTen-Backport 中向后移植到 Java 6 和 7,并在ThreeTenABP进一步适应 Android 。

Month

鉴于此处使用整月定义季节,我们可以使用方便的enum。这样的枚举值比单纯的整数值 (1-12) 要好,因为它们是类型安全的,并且可以保证您得到有效值。Month

EnumSet

AnEnumSet是一种跟踪枚举值子集的快速执行且内存紧凑的方法。

EnumSet<Month> spring = EnumSet.of( Month.MARCH , Month.APRIL );
EnumSet<Month> summer = EnumSet.of( Month.MAY , Month.JUNE , Month.JULY , Month.AUGUST );
EnumSet<Month> fall = EnumSet.of( Month.SEPTEMBER , Month.OCTOBER );
EnumSet<Month> winter = EnumSet.of( Month.NOVEMBER , Month.DECEMBER , Month.JANUARY , Month.FEBRUARY );

例如,我们获取特定时区的当前时刻。

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zoneId );

询问它的日期时间值Month

Month month = Month.from( zdt );

通过调用查找哪个季节EnumSet具有该特定月份值contains

if ( spring.contains( month ) ) {
    …
} else if ( summer.contains( month ) ) {
    …
} else if ( fall.contains( month ) ) {
    …
} else if ( winter.contains( month ) ) {
    …
} else {
    // FIXME: Handle reaching impossible point as error condition.
}

定义你自己的“季节”枚举

如果你在你的代码库中使用这个季节的想法,我建议定义你自己的枚举,“季节”。

基本枚举很简单:public enum Season { SPRING, SUMMER, FALL, WINTER; }. 但是我们还添加了一个静态方法of来查找哪个月份映射到哪个季节。

package work.basil.example;

import java.time.Month;

public enum Season {
    SPRING, SUMMER, FALL, WINTER;

    static public Season of ( final Month month ) {
        switch ( month ) {

            // Spring.
            case MARCH:  // Java quirk: An enum switch case label must be the unqualified name of an enum. So cannot use `Month.MARCH` here, only `MARCH`.
                return Season.SPRING;

            case APRIL:
                return Season.SPRING;

            // Summer.
            case MAY:
                return Season.SUMMER;

            case JUNE:
                return Season.SUMMER;

            case JULY:
                return Season.SUMMER;

            case AUGUST:
                return Season.SUMMER;

            // Fall.
            case SEPTEMBER:
                return Season.FALL;

            case OCTOBER:
                return Season.FALL;

            // Winter.
            case NOVEMBER:
                return Season.WINTER;

            case DECEMBER:
                return Season.WINTER;

            case JANUARY:
                return Season.WINTER;

            case FEBRUARY:
                return Season.WINTER;

            default:
                System.out.println ( "ERROR." );  // FIXME: Handle reaching impossible point as error condition.
                return null;
        }
    }

}

或者使用 Java 14 的 switch 表达式功能 ( JEP 361 )。

package work.basil.example;

import java.time.Month;
import java.util.Objects;

public enum Season
{
    SPRING, SUMMER, FALL, WINTER;

    static public Season of ( final Month month )
    {
        Objects.requireNonNull( month , "ERROR - Received null where a `Month` is expected. Message # 0ac03df9-1c5a-4c2d-a22d-14c40e25c58b." );
        return
                switch ( Objects.requireNonNull( month ) )
                        {
                            // Spring.
                            case MARCH , APRIL -> Season.SPRING;

                            // Summer.
                            case MAY , JUNE , JULY , AUGUST -> Season.SUMMER;

                            // Fall.
                            case SEPTEMBER , OCTOBER -> Season.FALL;

                            // Winter.
                            case NOVEMBER , DECEMBER , JANUARY , FEBRUARY -> Season.WINTER;
                        }
                ;
    }
}

以下是如何使用该枚举。

ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now ( zoneId );
Month month = Month.from ( zdt );
Season season = Season.of ( month );

转储到控制台。

System.out.println ( "zdt: " + zdt + " |  month: " + month + " | season: " + season );

zdt: 2016-06-25T18:23:14.695-04:00[美国/蒙特利尔] | 月份:六月 | 季节:夏季

于 2016-06-25T21:53:47.423 回答
1

好吧,它可能很简单

String getSeason(int month) {
    switch(month) {
          case 11:
          case 12:
          case 1:
          case 2:
                return "winter";
          case 3:
          case 4:
                return "spring";
          case 5:
          case 6:
          case 7:
          case 8:
                return "summer";
          default:
                return "autumn";
      }
}

我在评论中被指责为更好的解决方案:枚举:

public static Enum Season {
    WINTER(Arrays.asList(11,12,1,2)),
    SPRING(Arrays.asList(3,4)),
    SUMMER(Arrays.asList(5,6,7,8)),
    AUTUMN(Arrays.asList(9,10));

    Season(List<Integer> months) {
        this.monthlist = months;
    }
    private List<Integer> monthlist;
    public boolean inSeason(int month) {
        return this.monthlist.contains(month);  // if months are 0 based, then insert +1 before the )
    }

    public static Season seasonForMonth(int month) {
        for(Season s: Season.values()) {
            if (s.inSeason(month))
                 return s;
        }
        throw new IllegalArgumentException("Unknown month");
    }
}
于 2008-10-09T22:51:44.313 回答
1

我感到受宠若惊,但受宠若惊。所以我会做的。

这不仅检查月份,而且检查月份中的某一天。

import java.util.*

public String getSeason(Date today, int year){

    // the months are one less because GC is 0-based for the months, but not days.
    // i.e. 0 = January.
    String returnMe = "";

    GregorianCalender dateToday = new GregorianCalender(year, today.get(Calender.MONTH_OF_YEAR), today.get(Calender.DAY_OF_MONTH);
    GregorianCalender springstart = new GregorianCalender(year, 2, 1);
    GregorianCalender springend = new GregorianCalender(year, 3, 30);
    GregorianCalender summerstart = new GregorianCalender(year, 4, 1);
    GregorianCalender summerend = new GregorianCalender(year, 7, 31);
    GregorianCalender fallstart = new GregorianCalender(year, 8, 1);
    GregorianCalender fallend = new GregorianCalender(year, 9, 31);
    GregorianCalender winterstart = new GregorianCalender(year, 10, 1);
    GregorianCalender winterend = new GregorianCalender(year, 1, 28);

    if ((dateToday.after(springstart) && dateToday.before(springend)) || dateToday.equals(springstart) || dateToday.equals(springend)){
        returnMe = "Spring";

    else if ((dateToday.after(summerstart) && dateToday.before(summerend)) || dateToday.equals(summerstart) || dateToday.equals(summerend)){
        returnMe = "Summer";

    else if ((dateToday.after(fallstart) && dateToday.before(fallend)) || dateToday.equals(fallstart) || dateToday.equals(fallend)){
        returnMe = "Fall";

    else if ((dateToday.after(winterstart) && dateToday.before(winterend)) || dateToday.equals(winterstart) || dateToday.equals(winterend)){
        returnMe = "Winter";

    else {
        returnMe = "Invalid";
    }
    return returnMe;
}

我敢肯定这很可怕,并且可以改进。在评论中告诉我。

于 2008-10-09T23:13:56.980 回答
1
public class lab6project1 {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);

        System.out.println("This program reports the season for a given day and month");
        System.out.println("Please enter the month and day as integers with a space between the month and day");

        int month = keyboard.nextInt();
        int day = keyboard.nextInt();


        if ((month == 1) || (month == 2)) {
            System.out.println("The season is Winter");
        } else if ((month == 4) || (month == 5)) {
            System.out.println("The season is Spring");
        } else if ((month == 7) || (month == 8)) {
            System.out.println("The season is Summer");
        } else if ((month == 10) || (month == 11)) {
            System.out.println("The season is Fall");
        } else if ((month == 3) && (day <= 19)) {
            System.out.println("The season is Winter");
        } else if (month == 3) {
            System.out.println("The season is Spring");
        } else if ((month == 6) && (day <= 20)) {
            System.out.println("The season is Spring");
        } else if (month == 6) {
            System.out.println("The season is Summer");
        } else if ((month == 9) && (day <= 20)) {
            System.out.println("The season is Summer");
        } else if (month == 9) {
            System.out.println("The season is Autumn");
        } else if ((month == 12) && (day <= 21)) {
            System.out.println("The season is Autumn");
        } else if (month == 12) {
            System.out.println("The season is Winter");
        }
    }
}
于 2010-11-27T19:34:57.460 回答
1

尝试使用哈希表或枚举。您可以将日期转换为某个值(jan 1 为 1,...),然后为某个字段创建 bin。或者您可以对月份进行枚举。{一月:冬天,二月:冬天,...七月:夏天,等等}

于 2014-07-24T05:09:38.597 回答
0

由于在此范围内所有季节都是整月,因此您可以使用日期的月份进行切换:

switch (date.getMonth()) {
    case Calendar.JANUARY:
    case Calendar.FEBRUARY:
         return "winter";
    case Calendar.MARCH:
         return "spring";
    //etc
}

我建议使用所有 12 个日历常量来完成整个切换,而不是最后一个的默认值。然后,您可以确保您的输入是正确的,例如

default:
 throw new IllegalArgumentException();

在末尾。

根据您的用例,您可能还希望在季节中使用 Enum,而不是简单的字符串。

请注意 Date.getMonth() 方法已弃用,您应该改用 java.util.Calendar.get(Calendar.MONTH) 。(只需使用 calendar.setDate(yourDate) 将日期转换为日历)

于 2008-10-09T22:52:43.687 回答
0

简单的解决方案

 Calendar calendar = Calendar.getInstance();
 calendar.setTimeInMillis(timeInMills);
 int month = calendar.get(Calendar.MONTH);
 CurrentSeason = month == 11 ? 0 : (month + 1) / 3;
于 2016-09-01T08:45:54.783 回答
0

您的问题的标题非常笼统,因此大多数用户首先会想到天文季节。即使您的问题的详细内容仅限于自定义的日期范围,但这种限制可能只是由于无法计算天文情况造成的,所以我也敢于针对天文场景发布这个老问题的答案。

这里的大多数答案仅基于整月。我在这里举两个例子来解决天文季节和基于任意日期范围的季节。

a) 将任意日期范围映射到季节

在这里,我们肯定需要额外的信息,具体的时区或偏移量,否则我们无法java.util.Date使用月份和日期的组合将瞬间(如您输入的老式实例)转换为本地表示。为简单起见,我假设系统时区。

    // your input
    java.util.Date d = new java.util.Date();
    ZoneId tz = ZoneId.systemDefault();

    // extract the relevant month-day
    ZonedDateTime zdt = d.toInstant().atZone(tz);
    MonthDay md = MonthDay.of(zdt.getMonth(), zdt.getDayOfMonth());

    // a definition with day-of-month other than first is possible here
    MonthDay beginOfSpring = MonthDay.of(3, 1);
    MonthDay beginOfSummer = MonthDay.of(5, 1);
    MonthDay beginOfAutumn = MonthDay.of(9, 1);
    MonthDay beginOfWinter = MonthDay.of(11, 1);

    // determine the season
    Season result;

    if (md.isBefore(beginOfSpring)) {
        result = Season.WINTER;
    } else if (md.isBefore(beginOfSummer)) {
        result = Season.SPRING;
    } else if (md.isBefore(beginOfAutumn)) {
        result = Season.SUMMER;
    } else if (md.isBefore(beginOfWinter)) {
        result = Season.FALL;
    } else {
        result = Season.WINTER;
    }

    System.out.println(result);

我使用了一个简单的帮助枚举,例如public enum Season { SPRING, SUMMER, FALL, WINTER; }.

b) 天文季节

在这里,我们还需要一个额外的信息,即季节是在北半球还是在南半球。我的库Time4J基于使用 v5.2 版本的预定义枚举AstronomicalSeason提供以下解决方案:

    // your input
    java.util.Date d = new java.util.Date();
    boolean isSouthern = false;

    Moment m = TemporalType.JAVA_UTIL_DATE.translate(d);
    AstronomicalSeason result = AstronomicalSeason.of(m);

    if (isSouthern) { // switch to southern equivalent if necessary
        result = result.onSouthernHemisphere();
    }

    System.out.println(result);
于 2018-12-07T02:37:33.850 回答
0

如果只需要北半球的季节编号:

/**
 * @return 1 - winter, 2 - spring, 3 - summer, 4 - autumn
 */
private static int getDateSeason(LocalDate date) {
    return date.plus(1, MONTHS).get(IsoFields.QUARTER_OF_YEAR);
}

通过如何发现给定日期的季度?.


以下是如何计算给定日期的季节界限:

private static LocalDate atStartOfSeason(LocalDate date) {
    return date.plus(1, MONTHS).with(IsoFields.DAY_OF_QUARTER, 1).minus(1, MONTHS);
}

private static LocalDate afterEndOfSeason(LocalDate date) {
    return atStartOfSeason(date).plus(3, MONTHS);
}

通过如何在 java.util.Date 中获取当前季度的第一个日期和最后一个日期

于 2020-05-26T00:32:10.950 回答
0
import java.util.Scanner;

public class Season {

public static void main (String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter the month:");

        int mon=sc.nextInt();

        if(mon>12||mon<1)
        {
            System.out.println("Invalid month");
        }

        else if(mon>=3&&mon<=5)
        {
            System.out.println("Season:Spring");
        }

        else if(mon>=6&&mon<=8)
        {
            System.out.println("Season:Summer");
        }

        else if(mon>=9&&mon<=11)
        {
            System.out.println("Season:Autumn");
        }

        else if(mon==12||mon==1||mon==2)
        {
            System.out.println("Season:Winter");
        }
}
}
于 2021-06-05T07:49:24.197 回答