获取本日,本周,本月的开始时间戳和结束时间戳
这是我最近尝试写的一个程序,可能有许多不足之处,还请见谅。
这是一个类,类里面主要有两个方法。
一个是timeToTimestamp (),一个是getTime()。
前者负责将时间转化成时间戳,后者则负责判断filter值,然后设置相应的date时间。
注:filter=1 代表本日,filter=2 代表本周,filter=3代表本月。
class TimestampUtils{
private static long startTime = -1;
private static long endTime = -1;
public static void getTime (int filter){
Calendar cal =Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd" ); //设置星期一为一周的开始日
cal.setFirstDayOfWeek(Calendar.MONDAY);
switch(filter){
case 1://今天
startTime = timeToTimestamp(format.format(new Date())+" 00:00: 00");
endTime = timeToTimestamp(format.format(new Date())+" 23:59: 59");
break;
case 2://本周
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
startTime = timeToTimestamp(format.format(cal.getTime())+" 00:0 0:00");
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
endTime = timeToTimestamp(format.format(cal.getTime())+" 23:5 9:59");
break;
case 3://本月
cal.set(Calendar.DATE, cal.getActualMinimum(Calendar.DATE)); startTime = timeToTimestamp(format.format(cal.getTime())+" 00:0 0:00");
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE)) ;
endTime = timeToTimestamp(format.format(cal.getTime())+" 23:5 9:59");
break;
default:
break;
}
}
//将时间转换成时间戳
public static long timeToTimestamp (String dateTime){
SimpleDateFormat format2 = new SimpleDateFormat( "yyyy-MM-d d HH:mm:ss" );
long time = -1;
try {
time = format2.parse(dateTime).getTime();
} catch (ParseException e) {
printStackTrace();
}
return time;
}
}。