赞
踩
方法一:也是推荐使用的方法
//可以定义一个函数,函数的参数有小时、分、秒、相比今天的日期,今天就输入0,明天输入1,昨天输入-1,以此类推
//(毫秒是可选参数,可以输入也可以不输入,毫秒的取值范围是0到999)
private Date getNeedTime(int hour,int minute,int second,int addDay,int ...args){ Calendar calendar = Calendar.getInstance(); if(addDay != 0){ calendar.add(Calendar.DATE,addDay); } calendar.set(Calendar.HOUR_OF_DAY,hour); calendar.set(Calendar.MINUTE,minute); calendar.set(Calendar.SECOND,second); if(args.length==1){ calendar.set(Calendar.MILLISECOND,args[0]); } return calendar.getTime(); }
//下面用一个测试方法来测试一下上一个方法是否可行
@Test public void testGetNeedTime(){ Date start = getNeedTime(0,0,0,0); Date end = getNeedTime(23,59,59,0); Date now = new Date(); if(now.getTime() >= start.getTime() && now.getTime() <= end.getTime()){ System.out.println("当前时间在中间"); } System.out.println(start); System.out.println(end); }
//输出结果如下:
当前时间在中间 Tue Dec 27 00:00:00 CST 2016 Tue Dec 27 23:59:59 CST 2016
//如果想得到明天的0点0分0秒的时间和23点59分59秒的时间,只需要将日期加1就可以了
//运行结果如下:@Test public void testGetNeedTime(){ Date start = getNeedTime(0,0,0,1); Date end = getNeedTime(23,59,59,1); Date now = new Date(); if(now.getTime() >= start.getTime() && now.getTime() <= end.getTime()){ System.out.println("当前时间在中间"); } System.out.println(start); System.out.println(end); }
Wed Dec 28 00:00:00 CST 2016 Wed Dec 28 23:59:59 CST 2016
//如果想得到昨天的0点0分0秒的时间和23点59分59秒的时间,只需要将日期加-1就可以了@Test public void test4(){ Date start = getNeedTime(0,0,0,-1); Date end = getNeedTime(23,59,59,-1); Date now = new Date(); if(now.getTime() >= start.getTime() && now.getTime() <= end.getTime()){ System.out.println("当前时间在中间"); } System.out.println(start); System.out.println(end); }//运行结果如下:Mon Dec 26 00:00:00 CST 2016
Mon Dec 26 23:59:59 CST 2016
方法二:获取当天的0点0分0秒的时间和23点59分59秒的时间
@Test public void test(){ Date time = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String timeStr = format.format(time); SimpleDateFormat transfer = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date start = null; Date end = null; try { start = transfer.parse(timeStr+" 00:00:00"); end = transfer.parse(timeStr+" 23:59:59"); } catch (ParseException e) { } if(start.getTime()<= time.getTime() && end.getTime() >= time.getTime()){ System.out.println("在中间"); }System.out.println(start); System.out.println(end);}//运行结果如下所示:当前时间在中间 Tue Dec 27 00:00:00 CST 2016 Tue Dec 27 23:59:59 CST 2016
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。