Java - get Week Start and End

摘要:Java - get Week Start and End

這次的需求是,要取得每一天,那一天的那一週的七天資訊。

 

而客戶的第一天,為禮拜六,第七天為,禮拜日。

 

以下是計算第一天與第七天的程式碼

        Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("Asia/Taipei"));
        c.setTime(new Date());

        Date today = c.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Taipei"));

        int week = c.get(Calendar.DAY_OF_WEEK);
        // 六 = 7 ,日 = 1 ,一 = 2 , 二 = 3 , 三 = 4 , 四 = 5 , 五 = 6 ,
        log.info("week = " + week);

        Date startDate = null;
        Date endDate = null;

        //取得開始日期,及結束日期
        if(week==7)
        {
           startDate = today ;
           c.add(Calendar.DATE,6);
           endDate = c.getTime();
        }
        else
        {
           c.add(Calendar.DATE,-week);
           startDate = c.getTime();
           c.add(Calendar.DATE,6);
           endDate = c.getTime();
        }

        String strStartDate = sdf.format(startDate);
        String strEndDate = sdf.format(endDate);
        log.info(strStartDate + "~" + strEndDate);