用java写一个回文日期
时间: 2024-05-09 22:20:18 浏览: 8
以下是一个使用Java编写的回文日期程序:
```java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class PalindromeDate {
public static void main(String[] args) {
LocalDate date = LocalDate.of(1000, 1, 1);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMddyyyy");
while (!isPalindrome(date.format(formatter))) {
date = date.plusDays(1);
}
System.out.println(date.format(formatter));
}
public static boolean isPalindrome(String date) {
int length = date.length();
for (int i = 0; i < length / 2; i++) {
if (date.charAt(i) != date.charAt(length - i - 1)) {
return false;
}
}
return true;
}
}
```
这个程序使用Java 8中的`LocalDate`类来表示日期,并使用`DateTimeFormatter`类来格式化日期。它从1000年1月1日开始遍历所有日期,直到找到第一个回文日期为止。`isPalindrome`方法用于检查给定日期字符串是否是回文的。程序输出第一个回文日期:`11022011`,即2011年11月2日。