import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Main {
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
public static void main(String args[]) {
Date d = new Date();
// 月初
System.out.println("月初" + sdf.format(getMonthStart(d)));
// 月末
System.out.println("月末" + sdf.format(getMonthEnd(d)));
Date date = getMonthStart(d);
Date monthEnd = getMonthEnd(d);
while (!date.after(monthEnd)) {
System.out.println(sdf.format(date));
weekOfDate = getWeekOfDate(date);
System.out.println(weekOfDate);
date = getNext(date);
}
}
private static Date getMonthStart(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int index = calendar.get(Calendar.DAY_OF_MONTH);
calendar.add(Calendar.DATE, (1 - index));
return calendar.getTime();
}
private static Date getMonthEnd(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, 1);
int index = calendar.get(Calendar.DAY_OF_MONTH);
calendar.add(Calendar.DATE, (-index));
return calendar.getTime();
}
private static Date getNext(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, 1);
return calendar.getTime();
}
/** * 获取指定日期是星期几
* 参数为null时表示获取当前日期是星期几
* @param date
* @return
*/
public static String getWeekOfDate(Date date) {
String[] weekOfDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar calendar = Calendar.getInstance();
if(date != null){
calendar.setTime(date);
}
int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0){
w = 0;
}
return weekOfDays[w];
}
}
java 獲取本月一個月數據 及星期
最新推荐文章于 2023-06-20 14:38:47 发布