
java时间如何转换
用户关注问题
我有一个日期时间的字符串,想在Java中转换成Date或LocalDateTime对象,该怎么做?
使用DateTimeFormatter解析字符串为时间对象
在Java中,可以使用java.time包下的DateTimeFormatter类来定义时间格式,然后使用LocalDateTime.parse()方法将字符串转换为LocalDateTime对象。例如,定义格式:DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");然后调用LocalDateTime dateTime = LocalDateTime.parse(字符串, formatter);即可转换。
我想把Date或者LocalDateTime类型的时间转成特定格式的字符串,这个怎么实现?
使用DateTimeFormatter格式化时间对象为字符串
可以创建一个DateTimeFormatter对象并指定时间格式,然后调用时间对象的format方法进行格式化。例如,DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");String formattedDate = localDateTime.format(formatter);如果是旧版Date类型,可以先转换成Instant,再转换为LocalDateTime进行格式化。
我想知道Date和LocalDateTime之间如何相互转换,或者如何转换成Instant?
利用Instant和ZoneId实现Date与LocalDateTime的转换
Date类可以通过toInstant()方法转换成Instant对象;Instant再结合时区信息用LocalDateTime.ofInstant()方法转换成LocalDateTime。反之,可以通过LocalDateTime.atZone()转成ZonedDateTime,再转成Instant,最后用Date.from()生成Date对象。转换时需注意时区问题,通常使用系统默认时区即可。