[英]How to convert java.util.Date to java.time.LocalDate and preserve date/time
我正在尝试将java.util.Date
转换为java.time.LocalDate
:
[java.util.Date instance].toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
但是,有一种情况是[java.util.Date instance]
的白天时间为例如:22:25,我选择 ZoneId 像这样,例如: ZoneId.of("Asia/Singapore")
。
即将到来的LocalDate
将有不同的日期(因为该区域增加了 +6 小时),例如欧洲/明斯克:
printing java.util.Date: Thu Mar 04 22:25:00 CET 2021
printing converted java.util.Date to java.time.LocalDate with Europe/Minsk: 2021-03-04
printing converted java.util.Date to java.time.LocalDate with Asia/Singapore: 2021-03-05
并且我想在生成的LocalDate
中保留与该Date
实例中相同的日期。 一些方法如何解决这个问题? 我想可能有几种方法。
Instant
始终为您提供UTC
的日期时间,如果您想保持相同的日期,您需要使用UTC
的区域偏移量。
演示:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
String strDateTime = "10/02/2021 22:25";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm", Locale.ENGLISH);
Date date = sdf.parse(strDateTime);
Instant instant = date.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneOffset.UTC);
LocalDate localDate = zdt.toLocalDate();
System.out.println(localDate);
}
}
Output:
2021-10-02
从Trail: Date Time了解有关现代日期时间 API 的更多信息。
java.util
日期时间 API 及其格式 API、 SimpleDateFormat
已过时且容易出错。 建议完全停止使用它们并切换到现代日期时间 API 。 For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level仍然不符合 Java-8,检查Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project 。
您可以将其转换为即时,将时区设置为 UTC,因为java.util.Date使用的是 UTC。
public static LocalDate convert (Date date) {
return date.toInstant()
.atZone(ZoneId.of("UTC"))
.toLocalDate();
}
您可以简单地将Date
的值复制到LocalDate
而不转换数据:
LocalDate.of(date.getYear(), date.getMonth()+1, date.getDate());
对不起,你问的是不可能的。 尽管名称已过时,但Date
class 并不代表日期。 它代表一个时间点。 那时,新加坡和明斯克很容易有两个不同的日期。 由于您从一开始就没有日期,因此没有保留相同日期的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.