日期问题
Java代码 代码
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static int[] mouths = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] c = scanner.next().split("/");
Date[] dates =new Date[3];
dates[0] = new Date(Integer.parseInt(c[0]), Integer.parseInt(c[1]),Integer.parseInt(c[2]));
dates[1] = new Date(Integer.parseInt(c[2]), Integer.parseInt(c[1]),Integer.parseInt(c[0]));
dates[2] = new Date(Integer.parseInt(c[2]), Integer.parseInt(c[0]),Integer.parseInt(c[1]));
Arrays.sort(dates);
Set<String> set = new HashSet<>(); //避免相同的日期
for(int i = 0; i < 3; i++) {
String t = check(dates[i].year, dates[i].mouth, dates[i].day);
if(t != null && !set.contains(t)){
System.out.println(t);
set.add(t);
}
}
}
public static String check(int year, int mouth, int day) {
if(day == 0 || mouth > 12 || mouth == 0)
return null;
if(mouth != 2 && mouths[mouth] < day)
return null;
if(mouth == 2) {
if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
if(day > 29)
return null;
}else {
if(day > 28)
return null;
}
}
String t1 = String.format("%02d", mouth);
String t2 = String.format("%02d", day);
return year + "-" + t1 + "-" + t2;
}
public static class Date implements Comparable<Date>{
int year;
int mouth;
int day;
public Date(int year, int mouth, int day) {
if(year < 60)
this.year = year + 2000;
else
this.year = year + 1900;
this.mouth = mouth;
this.day = day;
}
@Override
public int compareTo(Date o) {
if(this.year == o.year) {
if(this.mouth == o.mouth){
return this.day - o.day;
}else {
return this.mouth - o.mouth;
}
}else {
return this.year - o.year;
}
}
}
}