In daily development, you will encounter calculations about dates, such as: the number of days in the current month, the number of days between two dates, the remaining days in the current month, etc...
Below is a demo about date calculation, which will be continuously updated later...
Get the number of days in the current month or the total number of days in a month
/**
* 获取日期当月的天数
* @param dateStr yyyy-MM 或者yyyy-MM-dd
* */
public static int getDaysByDate(String dateStr){
int year= Integer.parseInt(dateStr.substring(0,4));
int month=Integer.parseInt(dateStr.substring(5,7));
Calendar c = Calendar.getInstance();
c.set(year, month, 0);
return c.get(Calendar.DAY_OF_MONTH);
}
public static void main(String[] args) {
int daysByDate = getDaysByDate("2023-01");
System.out.println("2023年1月总天数:"+daysByDate);
}
The test example returns results:
2. The remaining days of the month
/**
* 当月剩余天数
* @param date 格式yyyy-MM-dd
* */
public static Integer monthEndNum(String date){
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
Date dateTime = null;
try {
dateTime = format.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar c = Calendar.getInstance();
c.setTime(dateTime);
int today = c.get(Calendar.DAY_OF_MONTH);
int last = c.getActualMaximum(Calendar.DAY_OF_MONTH);
return last - today;
}
public static void main(String[] args) {
Integer days = monthEndNum("2023-01-20");
System.out.println("2023年1月剩余天数:"+days);
}
The test example returns results:
The above is the sharing content of this issue. If you have good common public methods, you can also share them in the comment area to communicate together!