在 Java 中格式化时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/129181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:38:17  来源:igfitidea点击:

Formatting Timestamps in Java

javadate

提问by Craig H

Is there a way to format a UTC time into any arbitrary string format I want in java? Basically I was thinking of having some class take the timestamp and I pass it is string telling it how I want it formated, and it returns the formatted string for me. Is there a way to do this?

有没有办法在java中将UTC时间格式化为我想要的任意字符串格式?基本上我正在考虑让某个类获取时间戳,然后我传递它是字符串,告诉它我希望它如何格式化,它会为我返回格式化的字符串。有没有办法做到这一点?

采纳答案by Brendan Cashman

The java.text.SimpleDateFormat class provides formatting and parsing for dates in a locale-sensitive manner.

java.text.SimpleDateFormat 类以区域设置敏感的方式提供日期的格式设置和解析。

The javadoc header for SimpleDateFormatis a good source of detailed information. There is also a Java Tutorialwith example usages.

SimpleDateFormat的 javadoc 标头是详细信息的良好来源。还有一个带有示例用法的Java 教程

回答by Jay

The DateFormatclass or SimpleDateFormatshould get you there. For example, http://www.epochconverter.com/lists the following example to convert a epoch time to human readable timestamp with Java:

日期格式类或SimpleDateFormat的应该让你那里。例如,http://www.epochconverter.com/列出了以下使用 Java 将纪元时间转换为人类可读时间戳的示例:

String date = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));

回答by Maxim

Date instances are insufficient for some purposes.

日期实例对于某些目的是不够的。

Use Joda Timeinstead.

改用Joda 时间

Joda time integrates with Hibernate and other databases.

Joda 时间与 Hibernate 和其他数据库集成。

回答by Alex Miller

One gotcha to be aware of is that SimpleDateFormat is NOT thread-safe. Do not put it in a static field and use it from multiple threads concurrently.

需要注意的一个问题是 SimpleDateFormat 不是线程安全的。不要把它放在一个静态字段中并从多个线程并发使用它。