1. String 转化时间
默认情况下,Java日期是ISO8601
格式,因此任何表示ISO8601
格式的日期字符串,可以直接使用LocalDate.parse()
或LocalDateTime.parse()
方法。此处注意 LocalDateTime 与 LocalDate 是不同的
类 | 方法 | 字符串转化要求 |
---|---|---|
LocalDateTime |
parse(CharSequence text) |
字符串格式为日期 +时间 ,T 用来分割日期和时间,如“2018-12-05T12:12:12” ,否则将报错 |
LocalDate |
parse(CharSequence text) |
字符串必须完全符合年月日 格式,如“2018-12-05” ,否则将报错 |
1.1 直接解析
直接解析转化字符串为时间,字符串需符合 ISO8601
格式
// LocalDateTime,日期加时间
String str1="2020-12-05T12:12:23";
LocalDateTime time = LocalDateTime.parse(str1)
// LocalDate 日期
String str2="2020-12-05";
LocalDate date = LocalDate.parse(str2)
1.2 自定义解析
借助格式化日期时间格式化类 DateTimeFormatter
,需注意格式化的模式必须完全和待转化的字符串一致,比如待格式化字符串带有分信息 2020-12-05 12:12
,则模式必须为yyyy-MM-dd HH:mm
,否则会报错。另外也需要考虑时间进制的问题,比如本例中时间为 12:12
,这是 24 小时制才会有的,故其对应的时间模式为 HH:mm
,小写的 h
代表 12 小时制
// LocalDateTime,日期加时间
String str1="2020-12-05 12:12:23";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dataTime = LocalDateTime.parse(str1, dateTimeFormatter);
// LoaclDate 日期
String str2="2020-12-05";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.parse(str2, formatter);
2. 时间转化 String
把时间转化成想要的字符串相对简单,借助 DateTimeFormatter
很容易就可以完成
// DateTimeFormatter 指定模式,LocalDateTime.format()截取字符串
String yearMonth = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM"))
// DateTimeFormatter 指定模式,LocalDate.format()截取字符串,注意 LocalDate 只包含 年月日
String yearAndMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy_MM"))
3. 时间戳转化时间
Java 中时间戳一般可以通过 System
相关接口获取,其转化为日期时间时需要考虑时区,示例如下
// 根据 秒 时间戳配合 时区 将其转化为 时间
LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochSecond(1582703557), ZoneId.systemDefault())
// 系统 API 获取 毫秒 时间戳,再配合时区将其转化为时间
LocalDateTime time1 = LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis()), ZoneId.systemDefault())