1

我会从一个日期开始得到一年半月的数字。例如,我有 13-Mar-2012,结果是 6。

我已尝试使用 Calendar 类,但无法正常工作:

    Calendar cal = (GregorianCalendar) Calendar.getInstance();
    cal.set(Calendar.DAY_OF_MONTH,13);
    cal.set(Calendar.MONTH, 2);
    cal.set(Calendar.YEAR, 2012);
    int weekNum = cal.get(Calendar.WEEK_OF_YEAR);
    System.out.println("Weeknum:" + ((weekNum/2)));

谁能帮我?

4

4 回答 4

2

假设这里定义的半个月:http ://en.wikipedia.org/wiki/Half-month

  Calendar cal = (GregorianCalendar) Calendar.getInstance();
  cal.set(Calendar.DAY_OF_MONTH, 13);
  cal.set(Calendar.MONTH, 2);
  cal.set(Calendar.YEAR, 2012);
  // remember, we have a zero based month
  int halfMonth = cal.get( Calendar.MONTH ) * 2 + 1;
  // 1-15 is first half-month 16-end of month is second
  int remainder = cal.get( Calendar.DAY_OF_MONTH ) / 16; 
  halfMonth += remainder;

  System.out.println( halfMonth );
于 2012-04-27T20:37:13.000 回答
0
Calendar cal = (GregorianCalendar) Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH,13);
cal.set(Calendar.MONTH, 2);
cal.set(Calendar.YEAR, 2012);
int hafMonthCount = cal.get(Calendar.DAY_OF_YEAR) / 14 ;
//here you must multiply by 2 :)
System.out.println("HalfMonthCount:" + hafMonthCount );

- -更新

由于您使用的概念未在 Java 中实现(在法语中我们有 quizaine 的概念 14 天,但在英语中我不能说),您必须自己计算它。

于 2012-04-27T12:48:30.300 回答
0

通过示例显示您的代码发生了什么的详细信息。假设我们有以下四个不同的值WEEK_OF_YEAR

WEEK_OF_YEAR: 1
WEEK_OF_YEAR: 2
WEEK_OF_YEAR: 3
WEEK_OF_YEAR: 4

如果我们将这些值除以 2 会发生什么?

WEEK_OF_YEAR: 1          (weekNum/2) = 1/2 = 0 
WEEK_OF_YEAR: 2          (weekNum/2) = 2/2 = 1
WEEK_OF_YEAR: 3          (weekNum/2) = 3/2 = 1
WEEK_OF_YEAR: 4          (weekNum/2) = 4/2 = 2

所以你的代码的问题是它会在一年的第一周导致值 0。所以你想要在你的代码中做的就是(weekNum/2)((weekNum + 1)/2).

于 2012-05-02T11:27:25.190 回答
0
于 2016-08-30T06:35:55.837 回答