关于在java中,将Date型改成LocalDate型
来源:互联网 发布:163博客相册没有数据 编辑:程序博客网 时间:2024/06/17 20:55
Short answer:
Date input = new Date();LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Explanation:
Despite its name, java.util.Date
represents an instant on the time-line, not a "date". The actual data stored within the object is a long
count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).
The equivalent class to java.util.Date
in JSR-310 is Instant
, thus there is a convenient method toInstant()
to provide the conversion:
Date input = new Date();Instant instant = input.toInstant();
A java.util.Date
instance has no concept of time-zone. This might seem strange if you call toString()
on a java.util.Date
, because the toString
is relative to a time-zone. However that method actually uses Java's default time-zone on the fly to provide the string. The time-zone is not part of the actual state of java.util.Date
.
An Instant
also does not contain any information about the time-zone. Thus, to convert from an Instant
to a local date it is necessary to specify a time-zone. This might be the default zone - ZoneId.systemDefault()
- or it might be a time-zone that your application controls, such as a time-zone from user preferences. Use the atZone()
method to apply the time-zone:
Date input = new Date();Instant instant = input.toInstant();ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
A ZonedDateTime
contains state consisting of the local date and time, time-zone and the offset from GMT/UTC. As such the date - LocalDate
- can be easily extracted using toLocalDate()
:
Date input = new Date();Instant instant = input.toInstant();ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());LocalDate date = zdt.toLocalDate();
注:在jdk1.8中,调用toInstant()方法时会抛出错误,其实1.8中直接将Date对象调用toLocalDate()方法即可!
- 关于在java中,将Date型改成LocalDate型
- Java 8 中 Date与LocalDateTime、LocalDate、LocalTime互转
- Java 8 中 Date与LocalDateTime、LocalDate、LocalTime互转
- Java 8 中 Date与LocalDateTime、LocalDate、LocalTime互转
- Java8中 LocalDate和java.sql.Date的相互转换
- Java 8 中 Date与LocalDateTime、LocalDate、LocalTime互转
- Java 8 中 Date与LocalDateTime、LocalDate、LocalTime互转
- Java 8 中 Date与LocalDateTime、LocalDate、LocalTime互转
- Java 8 中 Date与LocalDateTime、LocalDate、LocalTime互转
- Java 时间类-Calendar、Date、LocalDate/LocalTime
- Java 时间类-Calendar、Date、LocalDate/LocalTime
- Java8中 Date和LocalDate的相互转换
- Date和LocalDate互转
- 在JDBC操作中关于java.util.Date跟java.sql.Date之间的转换问题
- 将ACCEPT改成非阻塞型
- 在java中如何将String类型转换成java.sql.Date类型
- 在java中怎样将Date类型转换成字符串类型
- LocalDate和Date的互换,以及LocalDate的使用
- OCR文字识别软件导出结果为PDF注意事项
- unity笔记-20161109
- linux 下用 man 命令不能查阅标准库函数的解决方案
- 摘要:2 网络驱动
- LBS地理位置距离计算方法之geohash算法
- 关于在java中,将Date型改成LocalDate型
- RatingBar 自定义 出现拉伸 重影
- Device Tree(一):背景介绍
- 彤姐的程序篇(四)关于支持可变参数的函数.
- Markdown生成效果
- oracle 创建表空间、用户、指定一般的权限
- RecyclerView 实现上浮的标题
- 2016/11/8
- Device Tree(二):基本概念