我有一个 int 格式的日期 DDMMYYYY,如何分隔日、月和年

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

int date1 = 22092021
int date2 = 03122021

我想知道哪个日期更早 假设每个月有 30 天

除了这种表示的明显问题(见评论)之外,这些部分可以像这样分开:

int y = date % 10000
date /= 10000
int m = date % 100
int d = date / 100

正如评论中所指出的,输入很可能是字符串形式的。您可以像这样从字符串中轻松解析 Date

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

然后你可以这样做来检查哪个日期更早:

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");
}

如果您有兴趣从 Date 实例中提取日、月和年,您可以创建一个小的实用方法将其转换为 Calendar,如下所示:

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

然后你可以用Calendar::get这样的方法提取它:

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));