java - Api 将日期时间作为数字返回,我怎样才能使它成为正确的日期?
问题描述
我正在使用一个外部 api(使用 MongoDB),它向我发送这样的日期格式:
"documentDate": 1574283600000,
我认为它的日期为:
"documentDate" : ISODate("2019-02-28T00:00:00.000+03:00"),
但它返回我的数字。我怎样才能使它成为这样一个合适的日期:
03/12/2019
解决方案
我会使用java.time
该值看起来像(并且很可能是)一个时刻,计为epoch milliseconds。您可以将其转换为一个Instant
,然后进一步将其转换为一个知道偏移量或时区的日期时间对象。
看看这个:
public static void main(String[] args) {
// your sample millis
long documentDateInMillis = 1574283600000L;
// parse it to a moment in time: an Instant
Instant instant = Instant.ofEpochMilli(documentDateInMillis);
// then create an offset aware datetime object by adding an actual offset
OffsetDateTime odt = OffsetDateTime.ofInstant(instant, ZoneOffset.of("+03:00"));
// print it in the default representation
System.out.println("Default formatting:\t" + odt);
// or in an ISO representation of the date only
System.out.println("ISO local date:\t\t"
+ odt.format(DateTimeFormatter.ISO_LOCAL_DATE));
// or in a custom representation (date only, too)
System.out.println("Custom formatting:\t"
+ odt.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
}
输出如下:
Default formatting: 2019-11-21T00:00+03:00
ISO local date: 2019-11-21
Custom formatting: 21/11/2019
推荐阅读
- arrays - 有没有办法将字符串数组拆分为 Bash 中的多个其他数组?
- java - java数组打印星号方块
- cryptography - 可证明的记录会话站点快照?是否有可能以不信任的方式进行?
- c++ - 类 WholeNumbers 的类型引用初始化无效
- javascript - 如何在复制到剪贴板时在 textarea 上添加新行?
- azure - 有什么方法可以在 zeppelin Notebook 中使用 Spark SQL 连接器
- bash - Bash:如何将 MONDDHR:MI 中的字符串转换为 Bash 中的日期?
- jdbc - CREATE LINKED TABLE 不适用于 PreparedStatement
- django-models - 参数@objname 不明确或声明的@objtype 错误
- c# - C# - 字符串未被识别为有效的 DateTime