代码:
/**
* 判断当天是否属于月份日历的第一行 (仅判断当月,不判断上一个月的日期)
* @param timeMills
* @return
*/
public static boolean isBelongFirstLineOfCalendar(long timeMills){
boolean isFirstLine = false;
Date tempDate = new Date(timeMills);
Calendar c = Calendar.getInstance();
c.setTime(tempDate);
//获取该月1号
Date firstDate = getFirstDayOfMonth(tempDate);
int firstWeek = getDayOfWeekInt(firstDate.getTime());//周一:0
//获取第一行起始和结束的日期
int lastMonthSize = firstWeek;//第一行上个月的日期个数
int thisMonthSize = 7 - firstWeek;
if(thisMonthSize < 0){
return false;
}
String firstStr = getYear(firstDate)+"-"+getMonth(firstDate)+"-"+getDay(firstDate)+" "+"00:00:00";
long firstDayTime = formatStrToDate("yyyy-MM-dd HH:mm:ss",firstStr).getTime();
long startDayTime = firstDayTime - 24*3600*1000L * lastMonthSize;
long endDayTime = firstDayTime + 24*3600*1000L * (thisMonthSize );
if(startDayTime < 0){
return false;
}
if(timeMills >= startDayTime && timeMills <= endDayTime){
isFirstLine = true;
}
return isFirstLine;
}
//-------date获取-年月日----------
public static int getYear(Date date) {
int year = 0;
try {
Calendar c = Calendar.getInstance();
c.setTime(date);
year = c.get(Calendar.YEAR);
} catch (Exception e) {
e.printStackTrace();
}
return year;
}
public static int getMonth(Date date) {
int month = 0;
try {
Calendar c = Calendar.getInstance();
c.setTime(date);
month = c.get(Calendar.MONTH) + 1;//函数返回0~11,结果要+1
} catch (Exception e) {
e.printStackTrace();
}
return month;
}
public static int getDay(Date date) {
int day = 0;
try {
Calendar c = Calendar.getInstance();
c.setTime(date);
day = c.get(Calendar.DAY_OF_MONTH);
} catch (Exception e) {
e.printStackTrace();
}
return day;
}
/**
* 返回指定日期的月的第一天
*
* @return
*/
public static Date getFirstDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH), 1);
return calendar.getTime();
}
public static int[] WEEKS4 = {6, 0, 1, 2, 3, 4, 5};
/**
* 获取当前星期几 (0~6)
*
* @param currentMills 当前时间戳
* @return int
*/
public static int getDayOfWeekInt(long currentMills) {
int res = 0;
try {
Calendar c = Calendar.getInstance();
c.setTime(new Date(currentMills));
int week = c.get(Calendar.DAY_OF_WEEK);//Calendar.SUNDAY = 1
res = WEEKS4[week - 1];
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
/**
* 格式化日期
*
* @param pattern 格式 ,例如:yyyy-MM-dd HH:mm:ss
* @param dateStr
* @return
*/
public static Date formatStrToDate(String pattern, String dateStr) {
Date date = new Date();
try {
if (dateStr != null) {
SimpleDateFormat format = new SimpleDateFormat(pattern);
date = format.parse(dateStr);
}
} catch (Exception e) {
e.printStackTrace();
}
return date;
}