如果我想让我的格式化日期看起来像:
2021-07-21 2:02:08.483 p.m. EDT
SimpleDateFormat
类能否打印“EDT”或“EST”,而无需我对其进行硬编码?格式说明符是什么?到目前为止,我有:
yyyy-MM-dd HH:mm:ss.SSS a
答案 0 :(得分:6)
java.util
日期时间 API 及其格式化 API SimpleDateFormat
已过时且容易出错。建议完全停止使用它们并切换到 modern Date-Time API*。
使用 java.time
(现代日期时间 API)的解决方案:
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd H:mm:ss a zzz", Locale.CANADA);
String strDateTime = ZonedDateTime.now(ZoneId.of("America/New_York")).format(dtf);
System.out.println(strDateTime);
}
}
输出:
2021-07-21 10:34:12 a.m. EDT
从 Trail: Date Time 了解有关现代 Date-Time API 的更多信息。
为了完整起见,下面给出了使用 SimpleDateFormat
的解决方案。
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd H:mm:ss a zzz", Locale.CANADA);
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String strDateTime = sdf.format(new Date());
System.out.println(strDateTime);
}
}
输出:
2021-07-21 10:36:52 a.m. EDT
* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 & 7. 如果您正在为 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring 和 How to use ThreeTenABP in Android Project。
答案 1 :(得分:0)
您只需要在您的模式中添加一个 z
- 但下次,refer to the docs。