简体   繁体   中英

Compare String date with today's date. Only compare month and day

I have string of date with format like this: 19930508. I want to use only 0508 from this string which is MMdd and than compare it with today's MMdd. The code i am using is:

Date todaysDate = new Date();
String dateTest = "19930508";
SimpleDateFormat df = new SimpleDateFormat("MMdd");
Date date = df.parse(dateTest);
String birthDate = df.format(date);

if(birthDate.equals(df.format(todaysDate))){do something}

The problem is the that birthdate formate is not working correctly neither todaysDate. Date date var print nothing and birthDate string print 0220 which makes no sense to me. Anyone with anyidea how can i work with this kind of formating and compare it with todaysdate ?

Using java.time from Java 8:

    MonthDay now = MonthDay.now();

    String dateTest = "19930508";
    DateTimeFormatter yearMonthDayFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
    MonthDay birthDay = MonthDay.parse(dateTest, yearMonthDayFormatter);

    if (birthDay.equals(now)) {
        System.out.println("same MMdd");
    } else {
        System.out.println("different MMdd");
    }
// works with java6
public class AnniversaryChecker {
    private final String dayInYear;

    public AnniversaryChecker() {
        this(new SimpleDateFormat("MMdd").format(new Date()));
    }

    // VisibleForTesting
    public AnniversaryChecker(String mmdd) {
        this.dayInYear = mmdd;
    }

    public boolean isAnniversary(String yyyyMMdd) {
        return yyyyMMdd.endsWith(dayInYear);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM