如何将任何时区的日期时间转换为JAVA中的UTC日期

huangapple go评论59阅读模式
英文:

How to convert any TimeZone dateTime to UTC Date in JAVA

问题

I have to use the date time which I receive by user, and convert that time to UTC from the given time. Right now, all the solutions are working, but not as I needed. First, it converts to the time zone, but I don't want to initially convert. I have to set that timezone on my date and then convert that time to UTC. Right now, each and every solution shows that I have to pass date and time, and then I am getting updated date and time with the time zone which I provide, and then converts to the UTC. This was not my question.

My user will send me date time of any timezone, and my server will be running on UTC time zone. I will get the zone id from the front end. I want to convert that date time to UTC and verify with my other conditions. It might be possible that I will get UTC-7 time in one request, and then after in next request I will get UTC+5:30. So, all the time should be converted to the UTC and I am not able to set timezone on date.

I wanted to set the specific timezone to date, and I am getting the date and time of that timezone, but I'm not able to set the exact timezone. Here, I am adding my code please tell me where I am wrong:

Calendar laCalendar = Calendar.getInstance();
laCalendar.set(2020, 8, 14, 00, 00);
Date losAngelesDate = laCalendar.getTime();
System.out.println("LA Date1===>" + losAngelesDate);

SimpleDateFormat simpleTimeFormatForUSA = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
simpleTimeFormatForUSA.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
String americaDateString = simpleTimeFormatForUSA.format(laCalendar.getTime());
SimpleDateFormat dateFormatUSA = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
losAngelesDate = dateFormatUSA.parse(americaDateString);

System.out.println("LA Date2===>" + losAngelesDate);
Date utcDate = losAngelesDate;
Calendar calendar = Calendar.getInstance();
calendar.setTime(utcDate);
TimeZone timeZone = TimeZone.getTimeZone("UTC");
SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
simpleTimeFormat.setTimeZone(timeZone);
String utcTime = simpleTimeFormat.format(calendar.getTime());
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
utcDate = dateFormat.parse(utcTime);
System.out.println("UTC date====>" + utcDate);

And my output is

LA Date1===>Mon Sep 14 00:00:56 UTC 2020
LA Date2===>Sun Sep 13 17:00:00 UTC 2020
UTC date====>Sun Sep 13 17:00:00 UTC 2020

Here you can see that my DateTime is converted, but the time zone is still UTC and I wanted to update that.


<details>
<summary>英文:</summary>
I have to use the date time which I receive by user, and convert that time to UTC from the given time. Right now, all the solutions are working, but not as I needed. First, it converts to the time zone, but I don&#39;t want to initially convert. I have to set that timezone on my date and then convert that time to UTC. Right now, each and every solution shows that I have to pass date and time, and then I am getting updated date and time with the time zone which I provide, and then converts to the UTC. This was not my question.
My user will send me date time of any timezone, and my server will be running on UTC time zone. I will get the zone id from the front end. I want to convert that date time to UTC and verify with my other conditions. It might be possible that I will get UTC-7 time in one request, and then after in next request I will get UTC+5:30. So, all the time should be converted to the UTC and I am not able to set timezone on date.
I wanted to set the specific timezone to date, and I am getting the date and time of that timezone, but I&#39;m not able to set the exact timezone. Here, I am adding my code please tell me where I am wrong:
Calendar laCalendar = Calendar.getInstance();
laCalendar.set(2020, 8, 14, 00, 00);
Date losAngelesDate = laCalendar.getTime();
System.out.println(&quot;LA Date1===&gt;&quot; + losAngelesDate);
SimpleDateFormat simpleTimeFormatForUSA = new SimpleDateFormat(&quot;MM/dd/yyyy hh:mm a&quot;);
simpleTimeFormatForUSA.setTimeZone(TimeZone.getTimeZone(&quot;America/Los_Angeles&quot;));
String americaDateString = simpleTimeFormatForUSA.format(laCalendar.getTime());
SimpleDateFormat dateFormatUSA = new SimpleDateFormat(&quot;MM/dd/yyyy hh:mm a&quot;);
losAngelesDate = dateFormatUSA.parse(americaDateString);
System.out.println(&quot;LA Date2===&gt;&quot; + losAngelesDate);
Date utcDate = losAngelesDate;
Calendar calendar = Calendar.getInstance();
calendar.setTime(utcDate);
TimeZone timeZone = TimeZone.getTimeZone(&quot;UTC&quot;);
SimpleDateFormat simpleTimeFormat = new SimpleDateFormat(&quot;MM/dd/yyyy hh:mm a&quot;);
simpleTimeFormat.setTimeZone(timeZone);
String utcTime = simpleTimeFormat.format(calendar.getTime());
SimpleDateFormat dateFormat = new SimpleDateFormat(&quot;MM/dd/yyyy hh:mm a&quot;);
utcDate = dateFormat.parse(utcTime);
System.out.println(&quot;UTC date====&gt;&quot; + utcDate);
And my output is
LA Date1===&gt;Mon Sep 14 00:00:56 UTC 2020
LA Date2===&gt;Sun Sep 13 17:00:00 UTC 2020
UTC date====&gt;Sun Sep 13 17:00:00 UTC 2020
Here you can see that my DateTime is converted, but time zone is still UTC and I wanted to update that.
</details>
# 答案1
**得分**: 2
以下是使用Java 8的Date/Time API编写的代码。
第一部分:
```java
public static void main(String[] args) {
System.out.println("UTC");
toTimeZone(new Date(), TimeZone.getTimeZone(ZoneId.of("UTC")));
System.out.println("America/Los_Angeles");
toTimeZone(new Date(), TimeZone.getTimeZone(ZoneId.of("America/Los_Angeles")));
}
public static void toTimeZone(Date date, TimeZone timeZone) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Instant epochMillisInstant = Instant.ofEpochMilli(calendar.getTimeInMillis());
LocalDateTime localDateTime = LocalDateTime.ofInstant(epochMillisInstant, ZoneId.systemDefault());
ZonedDateTime dateTimeToConvert = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
ZonedDateTime dateTimeWithTimeZone = dateTimeToConvert.withZoneSameInstant(timeZone.toZoneId());
String formattedDateForNewTimeZone = dateTimeWithTimeZone.format(DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm a"));
System.out.println(formattedDateForNewTimeZone);
}

第二部分(更简洁的版本):

public static void main(String[] args) {
    System.out.println("UTC");
    toTimeZone(LocalDateTime.now(), "UTC");
    System.out.println("America/Los_Angeles");
    toTimeZone(LocalDateTime.now(), "America/Los_Angeles");
}

private static void toTimeZone(LocalDateTime localDateTime, String timeZone) {
    ZonedDateTime localDateTimeToConvert = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
    ZonedDateTime zonedDateTime = localDateTimeToConvert.withZoneSameInstant(ZoneId.of(timeZone));
    String formattedDateForNewTimeZone = zonedDateTime.format(DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm a"));
    System.out.println(formattedDateForNewTimeZone);
}
英文:

Here, is how I would write it using Java 8 Date/Time APIs.

    public static void main(String[] args)
{
System.out.println(&quot;UTC&quot;);
toTimeZone(new Date(), TimeZone.getTimeZone(ZoneId.of(&quot;UTC&quot;)));
System.out.println(&quot;America/Los_Angeles&quot;);
toTimeZone(new Date(), TimeZone.getTimeZone(ZoneId.of(&quot;America/Los_Angeles&quot;)));
}
public static void toTimeZone(Date date, TimeZone timeZone)
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Instant epochMillisInstant = Instant.ofEpochMilli(calendar.getTimeInMillis());
LocalDateTime localDateTime = LocalDateTime.ofInstant(epochMillisInstant, ZoneId.systemDefault());
ZonedDateTime dateTimeToConvert = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
ZonedDateTime dateTimeWithTimeZone = dateTimeToConvert.withZoneSameInstant(timeZone.toZoneId());
String formattedDateForNewTimeZone = dateTimeWithTimeZone.format(DateTimeFormatter.ofPattern(&quot;MM/dd/yyyy hh:mm a&quot;));
System.out.println(formattedDateForNewTimeZone);
}

Using Just Java 8 Date/Time APIs - Shorter Version

public static void main(String[] args) {
System.out.println(&quot;UTC&quot;);
toTimeZone(LocalDateTime.now(),&quot;UTC&quot;);
System.out.println(&quot;America/Los_Angeles&quot;);
toTimeZone(LocalDateTime.now(),&quot;America/Los_Angeles&quot;);
}
private static void toTimeZone(LocalDateTime localDateTime, String timeZone) {
ZonedDateTime localDateTimeToConvert = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
ZonedDateTime zonedDateTime = localDateTimeToConvert.withZoneSameInstant(ZoneId.of(timeZone));
String formattedDateForNewTimeZone = zonedDateTime.format(DateTimeFormatter.ofPattern(&quot;MM/dd/yyyy hh:mm a&quot;));
System.out.println(formattedDateForNewTimeZone);
}

答案2

得分: 0

在将日历转换为日期之前,请将时区设置为您的偏好。

例如:

import java.util.Calendar;
import java.util.TimeZone;

public class Timezone {

    public static void main(String[] args) {
        Calendar laCalendar = Calendar.getInstance();
        TimeZone timezone = TimeZone.getTimeZone("UTC");
        laCalendar.set(2020, 8, 14, 00, 00);
        laCalendar.setTimeZone(timezone);
        java.util.Date losAngelesDate = laCalendar.getTime();
        System.out.println(losAngelesDate.toString());
    }
}
英文:

Before you convert the Calendar to a Date, set the Timezone to your preference.

For example:

import java.util.Calendar;
import java.util.TimeZone;
public class Timezone{
public static void main(String []args){
Calendar laCalendar = Calendar.getInstance();
TimeZone timezone = TimeZone.getTimeZone(&quot;UTC&quot;);
laCalendar.set(2020, 8, 14, 00, 00);
laCalendar.setTimeZone(timezone);
java.util.Date losAngelesDate = laCalendar.getTime();
System.out.println(losAngelesDate.toString());
}
}

huangapple
  • 本文由 发表于 2020年9月15日 00:42:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/63888534.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定