Date转换为LocalDateTime ⼀.在Java 8中将Date转换为LocalDateTime
⽅法1:
将Date转换为LocalDatetime,我们可以使⽤以下⽅法:
1.从⽇期获取ZonedDateTime并使⽤其⽅法toLocalDateTime()获取LocalDateTime
2.使⽤LocalDateTime的Instant()⼯⼚⽅法
⽰例:
package insping;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class Test {
public static void main(String[] args) {
Date date = new Date();
Instant instant = Instant();
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
System.out.println("Date = " + date);
System.out.println("LocalDateTime = " + localDateTime);
}
}
结果:
Date = Fri Jun 16 15:35:26 CST 2017
LocalDateTime = 2017-06-16T15:35:26.970
⽅法2:
我们也可以使⽤LocalDateTime的FactoryInput()⽅法使⽤系统的默认时区。
LocalDateTime localDateTime = LocalDateTime.Instant(), zoneId);
⼆.在Java 8中将LocalDateTime转换为Date
要将LocalDateTime转换回java.util.Date,我们可以使⽤以下步骤:
1.使⽤atZone()⽅法将LocalDateTime转换为ZonedDateTime
2.将ZonedDateTime转换为Instant,并从中获取Date
⽰例:
string转date的方法
package insping;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
public class Test {
public static void main(String[] args) {
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = w();
ZonedDateTime zdt = localDateTime.atZone(zoneId);
Date date = Date.Instant());
System.out.println("LocalDateTime = " + localDateTime);        System.out.println("Date = " + date);
}
}
结果:
LocalDateTime = 2017-06-16T15:38:48.580
Date = Fri Jun 16 15:38:48 CST 2017

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。