/** * 獲取指定日期所在月份開始的時間 * 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; }