問題描述
我有一個 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 天,我想知道哪個日期更早
參考解法
方法 1:
Apart from the obvious problems with this representation (see comments) the parts could be separated like this:
int y = date % 10000
date /= 10000
int m = date % 100
int d = date / 100
方法 2:
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));
(by Edgero30、Henry、Rohan Kumar)