0

我有一个String格式为String dob="02/26/2013";“mm/dd/yyy”格式的日期。它是出生日期,我想检查这个出生日期是否应该小于今天的日期。如何检查?

这是我的代码:

    Calendar cal = Calendar.getInstance();
    Date date = cal.getTime();
    SimpleDateFormat format1 = new SimpleDateFormat("MM-dd-yyyy");
    String date1 = format1.format(date);
    System.out.println(date1);
    String date2 = "2013/02/26";
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/mm/dd");
    Date convertedDate = dateFormat.parse(date2);
    System.out.println(convertedDate);

convertedDate打印为Sat Jan 26 00:02:00 IST 2013

4

5 回答 5

1
   SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

        Calendar cal = Calendar.getInstance();
        String strDate = sdf.format(cal.getTime());

        Date date1 = sdf.parse("02/26/2013");
        Date date2 = sdf.parse(strDate);

     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");
        }
于 2013-02-26T13:39:36.343 回答
1
    String dob="02/27/2013";
    Date today = new Date();

    try {
        Date dobDate = new SimpleDateFormat("MM/dd/yyyy").parse(dob);

        if (dobDate.compareTo(today) <= 0) {
            //before or equals today
            System.out.println("before");
        }
    } catch (ParseException e) {
        //handle exception
    }
于 2013-02-26T13:43:15.050 回答
1

new SimpleDateFormat("yyyy/mm/dd");是错的。mm是分钟,这就是为什么您在 1 月 26 日午夜后得到 2 分钟。更改mmMM

于 2013-02-26T14:12:35.003 回答
0

您可以查看 Joda 时间,也可以尝试将 String 转换为 Calendar 对象并根据需要使用 before 或 after 方法。有关更多帮助,请阅读DateFormatCalendar类的 Javadoc。

于 2013-02-26T13:40:48.223 回答
-2

你可以试试这个

String yourdate = "02/26/2013";
Date toDate = new SimpleDateFormat("MM/dd/yyyy").parse(yourdate);
long toDateAsTimestamp = toDate.getTime();
long currentTimestamp = System.currentTimeMillis();
long getRidOfTime = 1000 * 60 * 60 * 24;
long toDateAsTimestampWithoutTime = toDateAsTimestamp / getRidOfTime;
long currentTimestampWithoutTime = currentTimestamp / getRidOfTime;

if (toDateAsTimestampWithoutTime <= currentTimestampWithoutTime) {
    System.out.println("Display error.");
} else {
    System.out.println("All ok");
}
于 2013-02-26T13:42:15.697 回答