Java:如何获取日期而不是时间? [英] Java : How to get Date rather than time?

查看:131
本文介绍了Java:如何获取日期而不是时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以获得今天的日期,而不是时间?

Is it possible that i can get todays date , rather than time ??

这是我的代码

public static void main(String args[]) throws ParseException{   
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar = Calendar.getInstance();
    Date today = calendar.getTime();

}

为什么今天的日期显示为以前的日期??

Why is todays date is shown as before date ??

public class Ravi {

    public static void main(String args[]) throws ParseException {

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        System.out.println("Todays Date"+dateFormat.format(date));


        List currentObject = new ArrayList();

        currentObject.add("2012-09-27");

        Date ExpDate = dateFormat.parse((String) currentObject.get(0));

        System.out.println("ddd"+ExpDate);

        if (ExpDate.before(date)) {
            System.out.println("true");
        }

        else {
            System.out.println("false");
        }

    }

}


推荐答案

因为Date总是当前的时间,例如2012.09.27 12:45:23

Because Date is always the full current time e.g. 2012.09.27 12:45:23

虽然您的新的日期是2012.09.27 00:00:00因此输出正确。

Whilst your new Formated date is 2012.09.27 00:00:00 therefor the output is correct.

如果你想得到错误,你将需要设置小时,分钟和秒到0。

If you want to get false you will need to set hours, minutes and seconds to 0.

使用日历:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));

使用日期:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
System.out.println(dateFormat.format(date));

将日期与日历进行比较:

Comparing Dates with Calendar:

Calendar old = Calendar.getInstance();

old.set(Calendar.YEAR, 2011);

Calendar now = Calendar.getInstance();

old.before(now));

请注意,您可能需要将小时数和秒数设置为0。

Note you may want to set Hours Minutes and Seconds to 0.

这篇关于Java:如何获取日期而不是时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆