如何检查日期是否属于特定周或季度

时间:2017-04-18 14:51:07

标签: java

我需要一个java逻辑来检查某个日期(假设18-04-2017)是否属于当前周。 我们一年有四个季度 (1月,2月,3月) - 1Q (4月,5月,6月) - 2Q 所以我需要知道同一天是否属于当前季度。 将欣赏任何回复

1 个答案:

答案 0 :(得分:3)

我会说这些步骤,

1 - 计算一周的第一天和最后一天 Get current week start and end date in Java - (MONDAY TO SUNDAY)

2 - 检查日期是否介于该范围之间 Java: how do I check if a Date is within a certain range?      - 如果是的话,它会在一周内出现      - 如果不是,它不会

3 - 对季度做同样的事情,有开始和结束日期,并检查日期是否介于它们之间

   //import java.util.*;
   //import java.text.*;

public static void main(String[] args) {

    try {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        Date dateToTest = sdf.parse("18/04/2017");

        //lets assume the date source is a variable, hence extract year off of it

        String firstDateInString = "01/04/" +  Integer.toString(getYear(dateToTest));
        String secondDateInString = "01/07/" +  Integer.toString(getYear(dateToTest));
        String thirdDateInString = "01/10/" +  Integer.toString(getYear(dateToTest));

        Date firstDate = sdf.parse(firstDateInString);
        Date secondDate = sdf.parse(secondDateInString);
        Date thirdDate = sdf.parse(thirdDateInString);


        //check if in first quarter
        //if date is before April it has to be first Q
        if (dateToTest.before(firstDate)) {
            System.out.println("First Quarter");
            return;
        }
        //check if in second quarter
        //if date is before August it has to be first Q
        if (dateToTest.before(secondDate)) {
            System.out.println("Second Quarter");
            return;
        }

        //check if in 3rd quarter
        //if date is before August it has to be first Q
        if (dateToTest.before(thirdDate)) {
            System.out.println("third Quarter");
            return;
        }

        //well then the date must be in 4th quarter
        System.out.println("Fourth quarter");
    } catch (Exception err) {
        System.out.println(err);
    }
}

private static int getYear(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    return cal.get(Calendar.YEAR);

}

免责声明:此代码不是最佳方法。请注意,这里我不假设当前日期或年份。这里的目的是仅显示一般策略。