有关时间的实用小程序

1定时器  定时几点出发;2对当前时间的判断;3获取某天0点时间戳


1TimeUtil类

public class TimeUtil {

public staticDate buildTime(inthour,intminute,intsecond) {

Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.HOUR_OF_DAY, hour);

calendar.set(Calendar.MINUTE, minute);

calendar.set(Calendar.SECOND, second);

Date time = calendar.getTime();

if(time.before(newDate())) {

//若果当前时间已经是凌晨1点后,需要往后加1天,否则任务会立即执行。

//很多系统往往系统启动时就需要立即执行一次任务,但下面又需要每天凌晨1点执行,怎么办呢?

//很简单,就在系统初始化话时单独执行一次任务(不需要用定时器,只是执行那段任务的代码)

time =addDay(time,1);

}

returntime;

}

private staticDate addDay(Date date,intdays) {

Calendar startDT = Calendar.getInstance();

startDT.setTime(date);

startDT.add(Calendar.DAY_OF_MONTH, days);

returnstartDT.getTime();

}

}

1.2调用

Timer timer =newTimer();

timer.schedule(deleteTransTask, TimeUtil.buildTime(9,30,0),1000*60*60*24);



2isXXXXTime()类

public boolean  isXXXXTime() {

//9:30-11:30,13:00-15:00;

Calendar cal = Calendar.getInstance();//日期

//week hour minute minuteofday 当前时间

int    week = cal.get(Calendar.DAY_OF_WEEK);

int   hour = cal.get(Calendar.HOUR_OF_DAY);//获取小时

int   minute = cal.get(Calendar.MINUTE);//获取分钟

//用这个字段判断

int   minuteOfDay = hour *60+ minute;//从0:00分开是到目前为止的分钟数

//自己设定的时间范围

final intamStart =8*60+36;//起始时间的分钟数

final intpmStart =13*60+00;

final intamEnd =8*60+38;//结束时间的分钟数

final intpmEnd =13*60+10;

if(week ==1|| week ==7) {

return false;

}else if(minuteOfDay >= amStart && minuteOfDay <= amEnd) {//上午开盘

return true;

}else if(minuteOfDay >= pmStart && minuteOfDay <= pmEnd) {//下午开盘

return true;

}else{

return false;

}

}



3方法:返回当天零点的时间戳

public long  getDayBeginTimestamp() {

Date date =new Date();

GregorianCalendar gc =newGregorianCalendar();

gc.setTime(date);

Date date2 =newDate(date.getTime() - gc.get(gc.HOUR_OF_DAY) *60*60

*1000- gc.get(gc.MINUTE) *60*1000- gc.get(gc.SECOND)

*1000);

return  date2.getTime()/1000;

}

你可能感兴趣的:(有关时间的实用小程序)