java獲取當月的第一天或最后一天


方式共有兩種,使用java.util.Calendar日歷類實現

第一種:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
//獲得本月第一天
calendar.add(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
String firstDay = sdf.format(calendar.getTime());
System.out.println("firstDay:"+ firstDay);
//獲得本月最后一天
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
String lastDay = sdf.format(calendar.getTime());

第二種:

Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.DAY_OF_MONTH, 1);
System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
cal.roll(Calendar.DAY_OF_MONTH, -1);
System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));

 

參考文章:https://www.cnblogs.com/dongming-03/p/5628947.html

 

 

 

 

 

 

  


免責聲明!

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



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