java 根據傳入的時間獲取當前月的第一天的0點0分0秒和最后一天的23點59分59秒


/**
 * 獲取指定日期所在月份開始的時間
 * lkeji
 * @return
 */
    public static String getMonthBegin(String specifiedDay) {
        Date data = null;
        try {
            data = new SimpleDateFormat("yyyy-MM-dd").parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(data);
        //設置為1號,當前日期既為本月第一天
        c.set(Calendar.DAY_OF_MONTH, 1);
        //將小時至0
        c.set(Calendar.HOUR_OF_DAY, 0);
        //將分鍾至0
        c.set(Calendar.MINUTE, 0);
        //將秒至0
        c.set(Calendar.SECOND,0);
        //將毫秒至0
        c.set(Calendar.MILLISECOND, 0);
        // 本月第一天的時間戳轉換為字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date;
        try {
            date = sdf.parse(sdf.format(new Date(new Long(c.getTimeInMillis()))));
            //Date date = sdf.parse(sdf.format(new Long(s)));// 等價於
            return sdf.format(date);
        } catch (NumberFormatException e) {
            // TODO 自動生成的 catch 塊
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO 自動生成的 catch 塊
            e.printStackTrace();
        }
        return null;
    }


  /**
     * 獲取指定日期所在月份結束的時間
     * @return
     */
    public static String getMonthEnd(String specifiedDay) {
        Date data = null;
        try {
            data = new SimpleDateFormat("yyyy-MM-dd").parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(data);

        //設置為當月最后一天
        c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
        //將小時至23
        c.set(Calendar.HOUR_OF_DAY, 23);
        //將分鍾至59
        c.set(Calendar.MINUTE, 59);
        //將秒至59
        c.set(Calendar.SECOND, 59);
        //將毫秒至999
        c.set(Calendar.MILLISECOND, 999);
        // 本月第一天的時間戳轉換為字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date;
        try {
            date = sdf.parse(sdf.format(new Date(new Long(c.getTimeInMillis()))));
            //Date date = sdf.parse(sdf.format(new Long(s)));// 等價於
            return sdf.format(date);
        } catch (NumberFormatException e) {
            // TODO 自動生成的 catch 塊
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO 自動生成的 catch 塊
            e.printStackTrace();
        }
        return null;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM