DateTimeFormatter和sampledateformat的严格模式设定方法
时间: 2024-12-13 22:13:01 浏览: 70
在Java中,`DateTimeFormatter`和`SimpleDateFormat`是用于日期和时间格式化的两个主要类。它们都支持严格模式设定,但具体的实现方式有所不同。
### DateTimeFormatter
`DateTimeFormatter`是Java 8引入的日期时间格式化类,它位于`java.time.format`包中。`DateTimeFormatter`本身不支持直接设置严格模式,但可以通过`DateTimeFormatterBuilder`来构建一个严格模式的格式化器。
```java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.ResolverStyle;
public class DateTimeFormatterExample {
public static void main(String[] args) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseStrict()
.appendPattern("uuuu-MM-dd")
.toFormatter()
.withResolverStyle(ResolverStyle.STRICT);
LocalDate date = LocalDate.parse("2023-10-05", formatter);
System.out.println(date);
}
}
```
### SimpleDateFormat
`SimpleDateFormat`是Java 8之前用于日期时间格式化的类,它位于`java.text`包中。`SimpleDateFormat`可以通过`setLenient`方法来设置严格模式。
```java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false); // 设置为严格模式
try {
Date date = sdf.parse("2023-10-05");
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
```
### 总结
- `DateTimeFormatter`通过`DateTimeFormatterBuilder`和`ResolverStyle`来设置严格模式。
- `SimpleDateFormat`通过`setLenient(false)`方法来设置严格模式。
阅读全文
相关推荐


















