Java 将 LocalDateTime 转换为 UTC 中的 LocalDateTime
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34626382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert LocalDateTime to LocalDateTime in UTC
提问by Sarika.S
Convert LocalDateTime to LocalDateTime in UTC.
将 LocalDateTime 转换为 UTC 中的 LocalDateTime。
LocalDateTime convertToUtc(LocalDateTime date) {
//do conversion
}
I searched over net. But did not get a solution
我在网上搜索过。但是没有得到解决
回答by patelb
Use the below. It takes the local datetime and converts it to UTC using the timezone. You do not need to create it function.
使用下面的。它采用本地日期时间并使用时区将其转换为 UTC。您不需要创建它的功能。
ZonedDateTime nowUTC = ZonedDateTime.now(ZoneOffset.UTC);
System.out.println(nowUTC.toString());
If you need to obtain the LocalDateTime part of the ZonedDateTime then you can use the following.
如果您需要获取 ZonedDateTime 的 LocalDateTime 部分,则可以使用以下内容。
nowUTC.toLocalDateTime();
Here is a static method i use in my application to insert UTC time in mysql since i cannot add a default value UTC_TIMESTAMPto a datetime column.
这是我在应用程序中用于在 mysql 中插入 UTC 时间的静态方法,因为我无法将默认值UTC_TIMESTAMP添加到日期时间列。
public static LocalDateTime getLocalDateTimeInUTC(){
ZonedDateTime nowUTC = ZonedDateTime.now(ZoneOffset.UTC);
return nowUTC.toLocalDateTime();
}
回答by Leon Radley
There is an even simpler way
还有一个更简单的方法
LocalDateTime.now(Clock.systemUTC())
回答by Fatih Arslan
LocalDateTime does not contain Zone information. ZonedDatetime does.
LocalDateTime 不包含区域信息。ZonedDatetime 确实如此。
If you want to convert LocalDateTime to UTC, you need to wrap by ZonedDateTime fist.
如果要将 LocalDateTime 转换为 UTC,则需要先将 ZonedDateTime 包裹起来。
You can convert like the below.
你可以像下面这样转换。
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt.toLocalTime());
ZonedDateTime ldtZoned = ldt.atZone(ZoneId.systemDefault());
ZonedDateTime utcZoned = ldtZoned.withZoneSameInstant(ZoneId.of("UTC"));
System.out.println(utcZoned.toLocalTime());
回答by Andrew Feng
tldr: there is simply no way to do that; if you are trying to do that, you get LocalDateTimewrong.
tldr:根本没有办法做到这一点;如果你想这样做,你会得到LocalDateTime错误。
The reason is that LocalDateTimedoes not record Time Zone after instances are created. You cannot convert a date time without time zone to another date time based on a specific time zone.
原因是LocalDateTime在创建实例后不记录时区。您不能将没有时区的日期时间转换为基于特定时区的另一个日期时间。
As a matter of fact, LocalDateTime.now()should never be called in production code unless your purpose is getting random results. When you construct a LocalDateTimeinstance like that, this instance contains date time ONLY based on current server's time zone, which means this piece of code will generate different result if it is running a server with a different time zone config.
事实上,除非您的目的是获得随机结果,否则不应在生产代码中调用LocalDateTime.now()。当您像这样构造LocalDateTime实例时,此实例仅包含基于当前服务器时区的日期时间,这意味着如果这段代码运行具有不同时区配置的服务器,则会生成不同的结果。
LocalDateTimecan simplify date calculating. If you want a real universally usable data time, use ZonedDateTime or OffsetDateTime: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html.
LocalDateTime可以简化日期计算。如果您想要一个真正普遍可用的数据时间,请使用 ZonedDateTime 或 OffsetDateTime:https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html 。
回答by Ganesh
public static String convertFromGmtToLocal(String gmtDtStr, String dtFormat, TimeZone lclTimeZone) throws Exception{
if (gmtDtStr == null || gmtDtStr.trim().equals("")) return null;
SimpleDateFormat format = new SimpleDateFormat(dtFormat);
format.setTimeZone(getGMTTimeZone());
Date dt = format.parse(gmtDtStr);
format.setTimeZone(lclTimeZone);
return
format.format(dt); }
格式。格式(DT);}
回答by ddinh
you can implement a helper doing something like that :
你可以实现一个助手做这样的事情:
public static LocalDateTime convertUTCFRtoUTCZ(LocalDateTime dateTime) {
ZoneId fr = ZoneId.of("Europe/Paris");
ZoneId utcZ = ZoneId.of("Z");
ZonedDateTime frZonedTime = ZonedDateTime.of(dateTime, fr);
ZonedDateTime utcZonedTime = frZonedTime.withZoneSameInstant(utcZ);
return utcZonedTime.toLocalDateTime();
}
回答by slorinc
I personally prefer
我个人更喜欢
LocalDateTime.now(ZoneOffset.UTC);
as it is the most readable option.
因为它是最易读的选项。
回答by ManoDestra
Here's a simple little utility class that you can use to convert local date times from zone to zone, including a utility method directly to convert a local date time from the current zone to UTC (with main method so you can run it and see the results of a simple test):
这是一个简单的小实用程序类,可用于将本地日期时间从区域转换为区域,包括直接将本地日期时间从当前区域转换为 UTC 的实用程序方法(使用 main 方法,以便您可以运行它并查看结果一个简单的测试):
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public final class DateTimeUtil {
private DateTimeUtil() {
super();
}
public static void main(final String... args) {
final LocalDateTime now = LocalDateTime.now();
final LocalDateTime utc = DateTimeUtil.toUtc(now);
System.out.println("Now: " + now);
System.out.println("UTC: " + utc);
}
public static LocalDateTime toZone(final LocalDateTime time, final ZoneId fromZone, final ZoneId toZone) {
final ZonedDateTime zonedtime = time.atZone(fromZone);
final ZonedDateTime converted = zonedtime.withZoneSameInstant(toZone);
return converted.toLocalDateTime();
}
public static LocalDateTime toZone(final LocalDateTime time, final ZoneId toZone) {
return DateTimeUtil.toZone(time, ZoneId.systemDefault(), toZone);
}
public static LocalDateTime toUtc(final LocalDateTime time, final ZoneId fromZone) {
return DateTimeUtil.toZone(time, fromZone, ZoneOffset.UTC);
}
public static LocalDateTime toUtc(final LocalDateTime time) {
return DateTimeUtil.toUtc(time, ZoneId.systemDefault());
}
}
回答by anddero
Question?
题?
Looking at the answers and the question, it seems the question has been modified significantly. So to answer the current question:
查看答案和问题,似乎问题已被显着修改。所以要回答当前的问题:
Convert LocalDateTime to LocalDateTime in UTC.
将 LocalDateTime 转换为 UTC 中的 LocalDateTime。
Timezone?
时区?
LocalDateTime
does not store any information about the time-zone, it just basically holds the values of year, month, day, hour, minute, second, and smaller units. So an important question is: What is the timezone of the original LocalDateTime
?It might as well be UTC already, therefore no conversion has to be made.
LocalDateTime
不存储任何关于时区的信息,它只是基本上保存年、月、日、小时、分钟、秒和更小的单位的值。所以一个重要的问题是:原始的时区LocalDateTime
是什么?它也可能已经是 UTC,因此不必进行转换。
System Default Timezone
系统默认时区
Considering that you asked the question anyway, you probably meant that the original time is in your system-default timezone and you want to convert it to UTC. Because usually a LocalDateTime
object is created by using LocalDateTime.now()
which returns the current time in the system-default timezone. In this case, the conversion would be the following:
考虑到您无论如何都问了这个问题,您的意思可能是原始时间在您的系统默认时区中,并且您想将其转换为 UTC。因为通常一个LocalDateTime
对象是通过使用LocalDateTime.now()
which 返回系统默认时区中的当前时间来创建的。在这种情况下,转换将如下所示:
LocalDateTime convertToUtc(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}
An example of the conversion process:
转换过程示例:
2019-02-25 11:39 // [time] original LocalDateTime without a timezone
2019-02-25 11:39 GMT+1 // [atZone] converted to ZonedDateTime (system timezone is Madrid)
2019-02-25 10:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2019-02-25 10:39 // [toLocalDateTime] losing the timezone information
Explicit Timezone
显式时区
In any other case, when you explicitly specify the timezone of the time to convert, the conversion would be the following:
在任何其他情况下,当您明确指定要转换的时间的时区时,转换将如下所示:
LocalDateTime convertToUtc(LocalDateTime time, ZoneId zone) {
return time.atZone(zone).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}
An example of the conversion process:
转换过程示例:
2019-02-25 11:39 // [time] original LocalDateTime without a timezone
2019-02-25 11:39 GMT+2 // [atZone] converted to ZonedDateTime (zone is Europe/Tallinn)
2019-02-25 09:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2019-02-25 09:39 // [toLocalDateTime] losing the timezone information
The atZone()
Method
该atZone()
方法
The result of the atZone()
method depends on the time passed as its argument, because it considers all the rules of the timezone, including Daylight Saving Time (DST). In the examples, the time was 25th February, in Europe this means winter time (no DST).
该atZone()
方法的结果取决于作为其参数传递的时间,因为它考虑了时区的所有规则,包括夏令时 (DST)。在示例中,时间是 2 月 25 日,在欧洲,这意味着冬季时间(无 DST)。
If we were to use a different date, let's say 25th August from last year, the result would be different, considering DST:
如果我们使用不同的日期,假设是去年的 8 月 25 日,考虑到夏令时,结果会有所不同:
2018-08-25 11:39 // [time] original LocalDateTime without a timezone
2018-08-25 11:39 GMT+3 // [atZone] converted to ZonedDateTime (zone is Europe/Tallinn)
2018-08-25 08:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2018-08-25 08:39 // [toLocalDateTime] losing the timezone information
The GMT time does not change. Therefore the offsets in the other timezones are adjusted. In this example, the summer time of Estonia is GMT+3, and winter time GMT+2.
GMT 时间不变。因此调整了其他时区的偏移量。在此示例中,爱沙尼亚的夏令时为 GMT+3,冬令时为 GMT+2。
Also, if you specify a time within the transition of changing clocks back one hour. E.g. October 28th, 2018 03:30 for Estonia, this can mean two different times:
此外,如果您在将时钟回退一小时的过渡期间指定时间。例如,2018 年 10 月 28 日 03:30 对于爱沙尼亚,这可能意味着两个不同的时间:
2018-10-28 03:30 GMT+3 // summer time [UTC 2018-10-28 00:30]
2018-10-28 04:00 GMT+3 // clocks are turned back 1 hour [UTC 2018-10-28 01:00]
2018-10-28 03:00 GMT+2 // same as above [UTC 2018-10-28 01:00]
2018-10-28 03:30 GMT+2 // winter time [UTC 2018-10-28 01:30]
Without specifying the offset manually (GMT+2 or GMT+3), the time 03:30
for the timezone Europe/Tallinn
can mean two different UTC times, and two different offsets.
如果不手动指定偏移量(GMT+2 或 GMT+3),03:30
时区的时间Europe/Tallinn
可能意味着两个不同的 UTC 时间和两个不同的偏移量。
Summary
概括
As you can see, the end result depends on the timezone of the time passed as an argument. Because the timezone cannot be extracted from the LocalDateTime
object, you have to know yourself which timezone it is coming from in order to convert it to UTC.
如您所见,最终结果取决于作为参数传递的时间的时区。由于无法从LocalDateTime
对象中提取时区,因此您必须自己知道它来自哪个时区才能将其转换为 UTC。