gpt4 book ai didi

java - 如何在java中将时间戳日期转换为java.util日期(yyyy-mm-dd)

转载 作者:行者123 更新时间:2023-12-01 19:29:18 25 4
gpt4 key购买 nike

我从 Oracle 获取的日期采用 Timestamp 格式,但我需要将其转换为这种格式 2020-02-17 (yyyy-mm-dd) 格式,但目前在 postman 中,我收到的日期为 "2020-02-17T09:40:37.850+0000" 这种格式。
对此的任何帮助将非常感激

最佳答案

您可以轻松转换 java.sql.Timestampjava.time.LocalDate并获取日期 String通过格式化 LocalDate像这样:

public static void main(String[] args) {
// just a timestamp stub that takes "now"
java.sql.Timestamp ts = java.sql.Timestamp.from(Instant.now());
// convert it to a modern date object
LocalDate justDate = ts.toLocalDateTime().toLocalDate();
// print it using a suitable formatter
System.out.println(justDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
}

输出(今天)是

2020-02-17

您只需要 Java 8 或更高版本即可实现此目的,或者导入 backport library .

编辑

如果您不需要String但是一个java.util.Date ,用Instant来做只是,像这样:

public static void main(String[] args) {
// just a timestamp stub that takes "now"
Instant now = Instant.now();
Timestamp ts = Timestamp.from(now);
// create an Instant from the Timestamp
Instant timestampInstant = ts.toInstant();
// and then create a Date out from that Instant
java.util.Date creationDate = java.util.Date.from(now);

// do something with the Date here...
}

但请考虑使用 java.time只要有可能,这可能在您的域类中...

关于java - 如何在java中将时间戳日期转换为java.util日期(yyyy-mm-dd),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60259892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com