英文:
Convert a sql timestamp to java OffsetDateTime
问题
我需要将一些时间戳转换为 Java 中的 OffsetDateTime
。例如,我有以下时间:
2020-07-31 13:15:00.000000000 -03:00
我应该使用 SimpleDateFormat
来格式化这个时间,还是使用其他更直观的辅助方法?
英文:
I need to convert some timestamps to OffsetDateTime
in java. For example, I have the following time:
2020-07-31 13:15:00.000000000 -03:00
Should I use SimpleDateFormat
to format this or some other helpers that are more straightforward?
答案1
得分: 1
你需要使用DateTimeFormatter
(用于现代日期时间类的解析和格式化API),如下所示:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
OffsetDateTime odt = OffsetDateTime.parse("2020-07-31 13:15:00.000000000 -03:00",
DateTimeFormatter.ofPattern("u-M-d H:m:s.n ZZZZZ"));
System.out.println(odt);
}
}
输出:
2020-07-31T13:15-03:00
有关更多详细信息,请查阅 DateTimeFormatter
的文档。您还可以查看 Trail: Date Time 以了解更多关于现代日期时间API的信息。
注意: java.util
日期时间类已过时且容易出错,它们的格式化API SimpleDateFormat
也是如此。您应该完全停止使用它们。此外,OffsetDateTime
是现代日期时间API的一部分,而 SimpleDateFormat
则不适用于它。
如果您正在为Android项目进行操作,而您的Android API级别仍不符合Java-8,请查看 通过 desugaring 使用 Java 8+ API 和 如何在Android项目中使用 ThreeTenABP。
英文:
You need to use DateTimeFormatter
(the parsing and formatting API for the the modern date-time classes) as shown below:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
OffsetDateTime odt = OffsetDateTime.parse("2020-07-31 13:15:00.000000000 -03:00",
DateTimeFormatter.ofPattern("u-M-d H:m:s.n ZZZZZ"));
System.out.println(odt);
}
}
Output:
2020-07-31T13:15-03:00
Check the documentation of DateTimeFormatter
for more details on it. You can also check Trail: Date Time to learn more about the modern date-time API.
Note: java.util
date-time classes are outdated and error-prone and so is their formatting API, SimpleDateFormat
. You should stop using them completely. Moreover, OffsetDateTime
is part of the modern date-time API and SimpleDateFormat
doesn't fit with it.
If you are doing it for your Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论