0

用户使用年、月和日的下拉菜单选择日期。我必须将用户输入的日期与今天的日期进行比较。基本上看他们是不是同一个日期。例如,用户输入 02/16/2012。如果今天是 2012 年 2 月 16 日,那么我必须显示一条消息。我该怎么做?我尝试使用毫秒,但这给出了错误的结果。

4

5 回答 5

0
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date1 = sdf.parse("2012-05-17");
            Date date2 = sdf.parse("2012-01-01");

            System.out.println(sdf.format(date1));
            System.out.println(sdf.format(date2));

            if(date1.compareTo(date2)>0){
                System.out.println("Date1 is after Date2");
            }else if(date1.compareTo(date2)<0){
                System.out.println("Date1 is before Date2");
            }else if(date1.compareTo(date2)==0){
                System.out.println("Date1 is equal to Date2");
            }

或者

        if(date1.equals(date2)){
        System.out.println("Date1 is equal Date2");
    }

查看 如何比较日期

于 2012-05-16T19:09:47.070 回答
0

你要拿回什么样的物体?字符串、日历、日期?您可以获取该字符串并进行比较,至少您认为订单 YYYY MM DD /// DD MM YYY 会出现问题,在这种情况下,我建议根据您的规范 YYYYMMDD 创建一个自定义字符串,然后比较它们。

    Date d1 = new Date();
    Date d2 = new Date();

    String day1 = d1.getYear()+"/"+d1.getMonth()+"/"+d1.getDate(); 
    String day2 = d2.getYear()+"/"+d2.getMonth()+"/"+d2.getDate(); 
    if(day1.equals(day2)){
        System.out.println("Same day");
    }
于 2012-05-16T19:17:20.127 回答
0

Java中的日期是时间点,分辨率为“毫秒”。为了有效地比较两个日期,您需要首先将两个日期设置为“相同的时间”,以小时、分钟、秒和毫秒为单位。a 中的所有“setTime”方法java.util.Date都被弃用了,因为它们在国际化和本地化问题上不能正常工作。

为了“解决”这个问题,引入了一个新类GregorianCalendar

GregorianCalendar cal1 = new GregorianCalendar(2012, 11, 17);
GregorianCalendar cal2 = new GregorianCalendar(2012, 11, 17);
return cal1.equals(cal2); // will return true

GregorianCalendar 起作用的原因与年、月、日构造函数中的小时、分钟、秒和毫秒被初始化为零有关。您可以尝试java.util.Date通过使用不推荐使用的方法来近似这种情况setHours(0);但是,最终这将由于缺少setMillis(0). 这意味着要使用该Date格式,您需要获取毫秒并执行一些整数数学运算以将毫秒设置为零。

date1.setHours(0);
date1.setMinutes(0);
date1.setSeconds(0);
date1.setTime((date1.getTime() / 1000L) * 1000L);
date2.setHours(0);
date2.setMinutes(0);
date2.setSeconds(0);
date2.setTime((date2.getTime() / 1000L) * 1000L);
return date1.equals(date2); // now should do a calendar date only match

相信我,只需使用 Calendar / GregorianCalendar 类,它就是前进的方向(直到 Java 采用更复杂的东西,比如 joda time。

于 2012-05-16T19:19:09.530 回答
0

有两种方法可以做到。第一个是以相同的日期格式格式化日期或以字符串格式处理日期。

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        String date1 = sdf.format(selectedDate);
        String date2 = sdf.format(compareDate);
        if(date1.equals(date2)){
        }else{
        }

或者

    Calendar toDate = Calendar.getInstance();
    Calendar nowDate = Calendar.getInstance();
    toDate.set(<set-year>,<set-month>,<set-date->);  
    if(!toDate.before(nowDate))
    //display your report
    else
    // don't display the report
于 2012-05-16T19:20:28.220 回答
0

以上答案是正确的,但请考虑使用 JodaTime - 它更简单直观的 API。您可以设置DateTime使用with*方法并进行比较。

看看这个答案

于 2012-05-16T19:20:34.393 回答