String时间互转
两种办法:
- 使用DateFormat
- 使用DateTimeFormatter
一、DateFormat
-
String转时间
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String s ="2020-05-09"; String S2= "2020-05-10 16:21:02 "; Date date = format1.parse(s); Date date2 = format2.parse(S2); System.out.println("date="+date); System.out.println("date2="+date2); 结果: date=Sat May 09 00:00:00 CST 2020 date2=Sun May 10 16:21:02 CST 2020
-
时间转String
Date datex = new Date(); DateFormat format3 = new SimpleDateFormat("yyyy-MM-dd"); DateFormat format4 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("format3="+format3.format(datex)); System.out.println("format4="+format4.format(datex)); 结果: format3=2020-05-13 format4=2020-05-13 13:39:59
二、DateTimeFormatter
// String --> LocalDate
LocalDate localDate1 = LocalDate.parse("2020-12-07");
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
System.out.println(LocalDate.parse("2019-10-09").format(pattern));
// String --> LocalTime
LocalTime localTime = LocalTime.parse("07:43:53");
// String -->LocalDateTime
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDate = LocalDateTime.parse("2019-12-07 07:43:53",formatter1);
System.out.println("localDate"+localDate);
System.out.println("localTime"+localTime);
System.out.println("localDate"+localDate);
------------------
localDate 2019-12-07T07:43:53
localTime 07:43:53
localDate 2019-12-07T07:43:53
设置时区
TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));