获取一天的开始时间和结束时间

这是数据库中存放的是long类型的时间戳,将时间戳转换为Date类型后. 想要查询这一天中的数据:
    /**
     * @param args
     */
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        
        Date start = calendar.getTime();

        calendar.add(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.SECOND, -1);
        
        Date end = calendar.getTime();

        System.out.println(start);
        System.out.println(end);
    }

or:

    /**
     * @param args
     * @throws ParseException 
     */
    public static void main(String[] args) throws ParseException {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        
        Date start = calendar.getTime();

        calendar.add(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.SECOND, -1);
        
        Date end = calendar.getTime();

        System.out.println(start);
        System.out.println(end);
        
        /* other way */
        SimpleDateFormat formater = new SimpleDateFormat("yyyy/MM/dd");
        SimpleDateFormat formater2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        
        start = formater2.parse(formater.format(new Date())+ " 00:00:00");
        end = formater2.parse(formater.format(new Date())+ " 23:59:59");
        
        System.out.println(start);
        System.out.println(end);
    }

 

posted @ 2015-03-14 19:38  vaer  阅读(2179)  评论(0编辑  收藏  举报