/**
* 一天的零时刻
* @throws ParseException
*/
public static Date getDayZero(Date date) throws ParseException{
//y----年,不要写Y了,否则用sdf.parse(timeStr)得到的时间意想不到
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
String timeStr = sdf.format(date);
return sdf.parse(timeStr);
}
/**
* 一天的开始时间
* @throws ParseException
*/
public static void dayStat() throws ParseException{
Date date = new Date();
Date dayZero = getDayZero(date);
long timeMills = dayZero.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timeStr = sdf.format(dayZero);
System.out.println("一天的开始时间: "+ timeStr+" 毫秒值为: "+timeMills);
}
/**
* 一天的结束时间
* @throws ParseException
*/
public static void dayEnd() throws ParseException{
Date date = new Date();
Date dayZero = getDayZero(date);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
Calendar c = Calendar.getInstance();
c.setTime(dayZero);
//往后翻一天
c.add(Calendar.DAY_OF_MONTH, 1);
Date timeEnd = c.getTime();
String tEnd = sdf.format(timeEnd);
System.out.println("一天的开始时间: "+tEnd);
}
/**
* 一周的开始时间,即星期天的00:00:00
*/
public static void weekStat(){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
Calendar c = Calendar.getInstance();
int week = c.get(Calendar.DAY_OF_WEEK);
c.add(Calendar.DAY_OF_WEEK,-week+1);
Date timeEnd = c.getTime();
String tEnd = sdf.format(timeEnd);
System.out.println("周开始时间: "+tEnd);
}
/**
* 一周的结束时间,即下周一的00:00:00
*/
public static void weekEnd(){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
Calendar c = Calendar.getInstance();
c.setTime(date);
//当天是一周的第几天,星期天为第一天
int n = c.get(Calendar.DAY_OF_WEEK);
//往后翻8-n天,即为一周的结束时间,即下周天的00:00:00
c.add(Calendar.DAY_OF_MONTH, 7-n+1);
Date timeEnd = c.getTime();
String tEnd = sdf.format(timeEnd);
System.out.println("周结束时间: "+tEnd);
}
/**
* 一月的开始时间
*/
public static void monthStat(){
Date date = new Date();
//一月的开始时间,始终是01号00:00:00开始
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-01 00:00:00");
System.out.println("月开始时间: "+sdf.format(date));
}
/**
* 一月的结束时间
* @throws ParseException
*/
public static void monthEnd() throws ParseException{
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-01 00:00:00");
Date time = sdf.parse(sdf.format(date));
Calendar c = Calendar.getInstance();
c.setTime(time);
//往后翻一个月
c.add(Calendar.MONTH, 1);
Date timeEnd = c.getTime();
String tEnd = sdf.format(timeEnd);
System.out.println("月结束时间: "+tEnd);
}