如何从给定季度获得月份

xbl*_*3kx 2 java date java-time localdate

我试图从某个季度获得几个月。使用下面的代码,我成功地从 LocalDate.now() 实例中获取了当前季度的月份名称。

我如何从一个季度的字符串(例如“Q1”)中获得一个季度的月份?

int monthInt = Month.from(LocalDate.now()).firstMonthOfQuarter().getValue();
      for (int j = 1; j <= 3; j++) { //for each month in quarter
          System.out.println(Month.of(monthInt).name()); //January, February, March
          monthInt++;
      }
Run Code Online (Sandbox Code Playgroud)

Swe*_*per 5

我们可以找出JDK如何通过查看申报计算季度getFromIsoFields.QUARTER_OF_YEAR

public long getFrom(TemporalAccessor temporal) {
    if (isSupportedBy(temporal) == false) {
        throw new UnsupportedTemporalTypeException("Unsupported field: QuarterOfYear");
    }
    long moy = temporal.getLong(MONTH_OF_YEAR);
    return ((moy + 2) / 3);
}
Run Code Online (Sandbox Code Playgroud)

注意它是如何使用公式的quarter = (moy + 2) / 3。因此,要找到一个季度的开始月份,我们只需要根据moy-重新排列它moy = quarter * 3 - 2

你可以写一个这样的方法:

private static List<String> monthNamesFromQuarter(int quarter) {
    // you can do the validation of quarter yourself
    int start = quarter * 3 - 2;
    return IntStream.range(start, start + 3)
            .mapToObj(Month::of)
            .map(Month::name)
            .collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)


Bas*_*que 5

tl;博士

使用org.threeten.extra.YearQuarter类,随着QuarterZoneIdLocalDate,和Month

YearQuarter                         // Represent an entire quarter of a specific year.
.now( ZoneId.of( "Asia/Tokyo" ) )   // Determine the current quarter as seen via the wall-clock time used by the people of a particular region (a time zone). 
.with(                              // Move to another quarter.
    Quarter.valueOf( "Q1" )         // Or, `Quarter.of( 1 )` if starting with an integer number rather than a `String` object.
)                                   // Returns another `YearQuarter` object, rather than modifying the original.
.atDay( 1 )                         // Returns a `LocalDate` object.
.getMonth()                         // Returns a `Month` enum object.
.getDisplayName(                    // Automatically localize the name of the month. 
    TextStyle.FULL ,                // How long or abbreviated do you want the translation.
    Locale.US                       // Or Locale.CANADA_FRENCH and so on. 
)                                   // Returns a `String` object.
Run Code Online (Sandbox Code Playgroud)

一月

YearQuarterThreeTen-Extra

ThreeTen-EXTRA库有一个类,你可能会发现这项工作很有用:YearQuarter

获取当前季度。我们需要一个时区来确定当前日期,从而确定当前季度。对于任何给定时刻,日期在全球各地因时区而异。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
YearQuarter currentYearQuarter = YearQuarter.now( z ) ;
Run Code Online (Sandbox Code Playgroud)

但是您想通过解析字符串来确定四分之一。

如果您有一个类似于ISO 8601样式的字符串(该标准实际上并未指定季度),YYYY-QqYearQuarter可以直接解析.

String input = "2020-Q1" ;
YearQuarter yearQuarter = YearQuarter.parse( input ) ;
Run Code Online (Sandbox Code Playgroud)

如果您只有季度部分而没有年份,请使用Quarter枚举。如果您的输入字符串是Q1这样的,则用于valueOf检索匹配的枚举对象。

String input = "Q1" ;
Quarter quarter = Quarter.valueOf( input ) ;
Run Code Online (Sandbox Code Playgroud)

如果您有一个数字而不是一个字符串,即1or23or 4,则使用静态方法Quarter.of。顺便说一下,在您自己的代码中,您应该传递这些Quarter对象而不是单纯的整数或字符串,以使您的代码更具自文档性、提供类型安全性并确保有效值。

int input = 1 ; // Domain: 1, 2, 3, 4. 
Quarter quarter = Quarter.of( input ) ;
Run Code Online (Sandbox Code Playgroud)

将该Quarter实例应用于我们当前的YearQuarter实例以获取另一个YearQuarter实例。这些类使用不可变对象模式,因此我们不会修改现有实例,而是生成新实例。

YearQuarter yearQuarter = currentYearQuarter.with( quarter ) ;
Run Code Online (Sandbox Code Playgroud)

yearQuarter.toString(): 2019-Q1

从该年-季度获取第一个日期 ( LocalDate)、年-月 ( YearMonth) 和Month枚举对象。

LocalDate firstDate = yearQuarter.atDay( 1 ) ;
YearMonth yearMonth1 = YearMonth.from( firstDate ) ;
YearMonth yearMonth2 = yearMonth1.plusMonths( 1 ) ;
YearMonth yearMonth3 = yearMonth1.plusMonths( 2 ) ;
Run Code Online (Sandbox Code Playgroud)

生成一个包含自动本地化月份名称的字符串。

Locale locale = Locale.US ;  // Or Locale.CANADA_FRENCH and so on. 
String output1 = yearMonth1.getMonth().getDisplayName( TextStyle.FULL , locale ) ;
Run Code Online (Sandbox Code Playgroud)

一月


关于java.time

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

现在处于维护模式Joda-Time项目建议迁移到java.time类。

您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*

从哪里获得 java.time 类?

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多