将UTC字符串转换为UTC日期 [Android – Java]

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

Convert UTC String to UTC Date [Android - Java]

问题

我想要将UTC时间转换为日期应返回日期如下

预期结果是:```2020-09-01T08:44:25.654Z```

输出为 -> ```"Tue Sep 01 14:14:25 GMT+05:30 2020"```。

我得到了 ```UTC``` 但它是一个 ```String```,我想要相同的 ```format``` 但是使用 ```Date数据类型```。

我希望它是具有上述 ```UTC``` 格式的 ```Date```。

有人知道如何做到这一点吗

```java
public static Date convertToUtcTime(Date date) throws ParseException {
     SimpleDateFormat sdf = new SimpleDateFormat(DateFormats.yyyyMMddThhmmssZ);  //"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
     sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

     return sdf.parse(sdf.format(date));
}

同时我不想使用 toInstant 方法

[更新]

Date strFromDate;
try {
     strFromDate = AppUtils.convertToUtcTime(myCalendar.getTime());
} catch (ParseException e) {
     e.printStackTrace();
}

然后将 strFromDate 传递给API请求
我从 strFromDate 得到的结果不是预期的结果。


<details>
<summary>英文:</summary>

I want to convert UTC time to Date. It should return Date as

Expected result is : ```2020-09-01T08:44:25.654Z```
 
output is  -&gt; ```&quot;Tue Sep 01 14:14:25 GMT+05:30 2020&quot;```.

I am getting ```UTC``` but it is in ```String``` I want the same ```format``` in ```Date datatype```.

I want it as ```Date``` with the above ```UTC``` format.

Does anyone know how to get it?

public static Date convertToUtcTime(Date date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(DateFormats.yyyyMMddThhmmssZ); //"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

 return sdf.parse(sdf.format(date));

}


Also i dont want to use toInstant method

[UPDATED]

Date strFromDate;
try {
strFromDate = AppUtils.convertToUtcTime(myCalendar.getTime());
} catch (ParseException e) {
e.printStackTrace();
}


then passing strFromDate to api request
I am not getting expected result from strFromDate

</details>


# 答案1
**得分**: 1

以下是翻译好的内容:

谁是你最喜欢的演员?我们假设是[Amitabh Bachchan][1]。无论他扮演什么角色,他始终保持自我(这就是导演/制片人为什么会找他下一个角色的原因😊)。他的表演根据角色装点了他的外貌。导演通过他的表演技巧获得的是一个装饰的角色,根据指定的角色来代表他。然后,你可以说Amitabh Bachchan是一个“愤怒的年轻人”或者Amitabh Bachchan是一个“苦力”等等。

类似地,无论您要求`java.util.Date`采用什么样的外观(使用`SimpleDateFormat`),它始终表示自`1970-01-01T00:00:00Z`纪元以来的毫秒数。它没有任何时区或区域偏移信息。从这些毫秒数,Java根据您的JVM的时区计算日期和时间,然后将获得的日期和时间与您的JVM的时区相结合,最后在调用其`toString()`方法时返回字符串。我相信您已经知道当您使用`System.out.println`打印一个对象时,会打印对象的`toString()`方法返回的字符串。有关`java.util.Date`的`toString()`实现的更多详细信息,请参阅[此处][2]。`SimpeDateFormat`根据模式更改`java.util.Date`的外观。使用`SimpeDateFormat`得到的是一个装饰的字符串,根据指定的模式表示`Date`对象。然后,您可以将`Date`表示为`EEE MMMM dd, yyyy HH:mm`模式的字符串,或者表示为`yyyy-MM-dd HH:mm:ss`模式的字符串等。

**总结**:您不能通过指定不同的模式更改`Date`对象。如果您打印它,将始终获取其`toString()`函数返回的字符串。如果您想要不同的字符串,可以使用`SimpleDateFormat`来实现。

## 一些建议:
我建议您从过时且容易出错的`java.util`日期时间API和`SimpleDateFormat`切换到[现代](https://www.oracle.com/technical-resources/articles/java/jf14-date-time.html)`java.time`日期时间API以及相应的格式化API(包,`java.time.format`)。从**[教程:日期时间](https://docs.oracle.com/javase/tutorial/datetime/index.html)**了解更多关于现代日期时间API的信息。

如果您的Android API级别仍与Java 8不兼容,请查看https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project和[通过解糖获得的Java 8+ API](https://developer.android.com/studio/write/java8-support-table)。

  [1]: https://en.wikipedia.org/wiki/Amitabh_Bachchan
  [2]: http://hg.openjdk.java.net/jdk7u/jdk7u6/jdk/file/8c2c5d63a17e/src/share/classes/java/util/Date.java

<details>
<summary>英文:</summary>

Who is your favourite actor? Let&#39;s say it&#39;s [Amitabh Bachchan][1]. No matter what role he plays, he still remains himself (and that is why directors/producers go to him with next offer &#128522;). His acting decorates his look as per the role. What directors get using his acting skill is a decorated character representing him as per the specified role. And, then you say Amitabh Bachchan as an `angry young man` OR Amitabh Bachchan as a `coolie` etc.)

Similarly, no matter what kind of look you ask `java.util.Date` to take (using `SimpleDateFormat`), it always represents the no. of milliseconds from the epoch of `1970-01-01T00:00:00Z`. It does not have any time-zone or zone-offset information.  From this milliseconds, Java calculates the date and time based on the time-zone of your JVM and then combines the obtained date and time with the time-zone of your JVM and finally returns the string when its `toString()` method is called. I believe you already know that when you print an object using `System.out.println`, the string returned by the object&#39;s `toString()` method gets printed. Check [this][2] for more details of the `toString()` implementation of `java.util.Date`. A `SimpeDateFormat` changes the look of `java.util.Date` as per the pattern. What you get using a `SimpeDateFormat` is a decorated string representing the `Date` object as per the specified pattern. And, then you say `Date` as a string of `EEE MMMM dd, yyyy HH:mm` pattern OR `Date` as a string of `yyyy-MM-dd HH:mm:ss` pattern etc.

**The summary is**: You can not change `Date` object by specifying different patterns. If you print it, you will always get the string returned by its `toString()` function. If you want a different string, you can do so by using `SimpleDateFormat`.

## A recommendation:
I recommend you switch from the outdated and error-prone `java.util` date-time API and `SimpleDateFormat` to the [modern](https://www.oracle.com/technical-resources/articles/java/jf14-date-time.html) `java.time` date-time API and the corresponding formatting API (package, `java.time.format`). Learn more about the modern date-time API from **[Trail: Date Time](https://docs.oracle.com/javase/tutorial/datetime/index.html)**.

If your Android API level is still not compliant with Java8, check https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project and [Java 8+ APIs available through desugaring](https://developer.android.com/studio/write/java8-support-table).

  [1]: https://en.wikipedia.org/wiki/Amitabh_Bachchan
  [2]: http://hg.openjdk.java.net/jdk7u/jdk7u6/jdk/file/8c2c5d63a17e/src/share/classes/java/util/Date.java

</details>



huangapple
  • 本文由 发表于 2020年9月13日 17:01:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63868966.html
匿名

发表评论

匿名网友

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

确定