首页 > 其他分享 >005 日期时间与字符串转换

005 日期时间与字符串转换

时间:2022-12-20 19:45:51浏览次数:46  
标签:return String 005 pattern 日期 DateTimeFormatter LocalDateTime 字符串 LocalDate

1. 字符串转LocalDate

1 public static LocalDate parseDateString(String dateString, String pattern){
2     try{
3         DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
4         return LocalDate.parse(dateString, formatter);
5     }catch (DateTimeParseException ex){
6         ex.printStackTrace();
7         return null;
8     }
9 }

2. LocalDate转字符串

1 public static String formatDate(LocalDate date, String pattern){
2     DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern);
3     return date.format(dateFormatter);
4 }

3. 字符串转LocalDateTime

1 public static LocalDateTime parseTimeString(String timeString, String pattern){
2     try{
3         DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
4         return LocalDateTime.parse(timeString, formatter);
5     }catch (DateTimeParseException ex){
6         ex.printStackTrace();
7         return null;
8     }
9 }

4. LocalDateTime转字符串

1 public static String formatTime(LocalDateTime time, String pattern){
2     DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern);
3     return time.format(dateFormatter);
4 }

测试代码:

1 public static void main(String[] args) {
2     LocalDate date = parseDateString("2022年12月8日", "y年M月d日");
3     System.out.println(formatDate(date, "MM/dd/yyyy"));
4 
5     LocalDateTime time = parseTimeString("2022年12月8日 8:22:5","y年M月d日 H:m:s");
6     System.out.println(formatTime(time, "yyyy-MM-dd HH时mm分ss秒"));
7 }

输出结果是:

12/08/2022
2022-12-08 08时22分05秒

标签:return,String,005,pattern,日期,DateTimeFormatter,LocalDateTime,字符串,LocalDate
From: https://www.cnblogs.com/java369/p/16994942.html

相关文章