[Solved] I have a date in int format DDMMYYYY, how can I separate day and month and year [closed]


As pointed out in comments, it’s most likely that input might be coming as string. You can easily parse Date from string like this:

private static Date getDate(String dateStr) throws ParseException {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("ddMMyyyy");
    return simpleDateFormat.parse(dateStr);
}

Then you can do something like this to check which date is older:

String date1 = "22092021";
String date2 = "03122021";

Date d1 = getDate(date1);
Date d2 = getDate(date2);

if (d1.compareTo(d2) < 0) {
    System.out.println("d1 is older than d2");
} else if (d1.compareTo(d2) > 0) {
    System.out.println("d2 is older than d1");
} else {
    System.out.println("both are equal");
}

In case you’re interested in extracting day, month and year from your Date instance, you can create a small utility method to convert it to Calendar like this:

private static Calendar toCalendar(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    return cal;
}

Then you can extract it with Calendar::get methods like this:

Calendar c1 = toCalendar(d1);
System.out.printf("%d %d %d\n", c1.get(Calendar.DAY_OF_MONTH), c1.get(Calendar.MONTH), c1.get(Calendar.YEAR));

Calendar c2 = toCalendar(d2);
System.out.printf("%d %d %d\n", c2.get(Calendar.DAY_OF_MONTH), c2.get(Calendar.MONTH), c2.get(Calendar.YEAR));

1

solved I have a date in int format DDMMYYYY, how can I separate day and month and year [closed]