SimpleDateFormat 和 DateTimeFormatter的使用方式
时间: 2023-08-03 10:02:26 浏览: 147
Sure! Here's how you can use SimpleDateFormat and DateTimeFormatter in Android:
1. SimpleDateFormat:
- Create an instance of SimpleDateFormat by specifying the desired pattern.
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
```
- Format a Date object to a formatted string using the format() method.
```java
String formattedDate = sdf.format(new Date());
```
- Parse a formatted string back to a Date object using the parse() method.
```java
Date date = sdf.parse("2022-01-01 12:00:00");
```
2. DateTimeFormatter (Java 8+):
- Create an instance of DateTimeFormatter by specifying the desired pattern.
```java
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
```
- Format a LocalDateTime object to a formatted string using the format() method.
```java
String formattedDateTime = dtf.format(LocalDateTime.now());
```
- Parse a formatted string back to a LocalDateTime object using the parse() method.
```java
LocalDateTime dateTime = LocalDateTime.parse("2022-01-01 12:00:00", dtf);
```
Remember to handle any potential ParseException when parsing the formatted string back to a Date or LocalDateTime object.
These are just basic examples, and you can customize the patterns and use additional methods provided by SimpleDateFormat and DateTimeFormatter based on your specific requirements.
阅读全文
相关推荐
















