Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

java - 如何从给定季度获得月数(How to get Months from a given quarter)

I'm trying to get Months from a certain quarter.

(我正在尝试从某个季度获得月数。)

Using the code below, I successfully get the names of the months in the current quarter from the LocalDate.now() instance.

(使用下面的代码,我从LocalDate.now()实例成功获取了当前季度的月份名称。)

How would I get a quarter's months from just a quarter String (eg "Q1")?

(我怎样才能从四分之一的String(例如“ 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++;
      }
  ask by xblaz3kx translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For quarter > firstmonth the rule is

(对于quarter > firstmonth ,规则是)

Q1 -> 1
Q2 -> 4
Q3 -> 7
Q4 -> 10

With math : quarterValue *3 -2

So applying this in Java :

(所以在Java中应用它:)

String quarter = "Q1";
int monthInt = Integer.parseInt(quarter.replaceAll("\D", "")) * 3 - 2;
for (int j = 0; j < 3; j++) {
    System.out.println(Month.of(monthInt + j).name());
}

List<String> quarters = Arrays.asList("Q1", "Q2", "Q3", "Q4");
for (String quarter : quarters) {
    System.out.print(quarter);
    int monthInt = Integer.parseInt(quarter.replaceAll("\D", "")) * 3 - 2;
    for (int j = 0; j < 3; j++) {
        System.out.print(" " + Month.of(monthInt + j).name());
    }
    System.out.println();
}

Q1 JANUARY FEBRUARY MARCH
Q2 APRIL MAY JUNE
Q3 JULY AUGUST SEPTEMBER
Q4 OCTOBER NOVEMBER DECEMBER

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...