Java 将 Instant 格式化为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25229124/
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
Format Instant to String
提问by Dag
I'm trying to format an Instant to a String using the new java 8 time-api and a pattern:
我正在尝试使用新的 java 8 time-api 和模式将 Instant 格式化为字符串:
Instant instant = ...;
String out = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(instant);
Using the code above I get an Exception which complains an unsupported field:
使用上面的代码我得到一个异常,它抱怨一个不受支持的字段:
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra
at java.time.Instant.getLong(Instant.java:608)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
...
采纳答案by JodaStephen
Time Zone
时区
To format an Instant
a time-zoneis required. Without a time-zone, the formatter does not know how to convert the instant to human date-time fields, and therefore throws an exception.
要格式化的Instant
一个时区是必需的。如果没有时区,格式化程序不知道如何将即时字段转换为人工日期时间字段,因此会引发异常。
The time-zone can be added directly to the formatter using withZone()
.
可以使用 将时区直接添加到格式化程序中withZone()
。
DateTimeFormatter formatter =
DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
.withLocale( Locale.UK )
.withZone( ZoneId.systemDefault() );
Generating String
生成字符串
Now use that formatter to generate the String representation of your Instant.
现在使用该格式化程序生成 Instant 的字符串表示形式。
Instant instant = Instant.now();
String output = formatter.format( instant );
Dump to console.
转储到控制台。
System.out.println("formatter: " + formatter + " with zone: " + formatter.getZone() + " and Locale: " + formatter.getLocale() );
System.out.println("instant: " + instant );
System.out.println("output: " + output );
When run.
跑的时候。
formatter: Localized(SHORT,SHORT) with zone: US/Pacific and Locale: en_GB
instant: 2015-06-02T21:34:33.616Z
output: 02/06/15 14:34
回答by Dag
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String text = date.toString(formatter);
LocalDate date = LocalDate.parse(text, formatter);
I believe this might help, you may need to use some sort of localdate variation instead of instant
我相信这可能会有所帮助,您可能需要使用某种本地日期变化而不是即时
回答by Sergey Ponomarev
The Instant
class doesn't contain Zone information, it only stores timestamp in milliseconds from UNIX epoch, i.e. 1 Jan 1070 from UTC.
So, formatter can't print a date because date always printed for concrete time zone.
You should set time zone to formatter and all will be fine, like this :
本Instant
类不包含区的信息,它只存储毫秒时间戳记UNIX时代,即1070年1月1日从UTC。因此,格式化程序无法打印日期,因为日期总是针对具体时区打印。您应该将时区设置为格式化程序,一切都会好起来的,如下所示:
Instant instant = Instant.ofEpochMilli(92554380000L);
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(Locale.UK).withZone(ZoneOffset.UTC);
assert formatter.format(instant).equals("07/12/72 05:33");
assert instant.toString().equals("1972-12-07T05:33:00Z");
回答by u8798869
public static void main(String[] args) {
DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault());
System.out.println(DATE_TIME_FORMATTER.format(new Date().toInstant()));
}
回答by Nik.exe
Or if you still want to use formatter created from pattern you can just use LocalDateTime instead of Instant:
或者,如果您仍然想使用从模式创建的格式化程序,您可以使用 LocalDateTime 而不是 Instant:
LocalDateTime datetime = LocalDateTime.now();
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(datetime)
回答by Archimedes Trajano
DateTimeFormatter.ISO_INSTANT.format(Instant.now())
This saves you from having to convert to UTC. However, some other language's time frameworks may not support the milliseconds so you should do
这使您不必转换为 UTC。但是,某些其他语言的时间框架可能不支持毫秒,因此您应该这样做
DateTimeFormatter.ISO_INSTANT.format(Instant.now().truncatedTo(ChronoUnit.SECONDS))
回答by cs_pupil
Instants are already in UTC and already have a default date format of yyyy-MM-dd. If you're happy with that and don't want to mess with time zones or formatting, you could also toString()
it:
Instants 已经是 UTC 并且已经具有 yyyy-MM-dd 的默认日期格式。如果您对此感到满意并且不想弄乱时区或格式,您也toString()
可以:
Instant instant = Instant.now();
instant.toString()
output: 2020-02-06T18:01:55.648475Z
Don't want the T and Z?(Z indicates this date is UTC. Z stands for "Zulu" aka "Zero hour offset" aka UTC):
不想要 T 和 Z?(Z 表示这个日期是 UTC。Z 代表“祖鲁语”又名“零时差”又名 UTC):
instant.toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.663763
Want milliseconds instead of nanoseconds?(So you can plop it into a sql query):
想要毫秒而不是纳秒?(因此您可以将其放入 sql 查询中):
instant.truncatedTo(ChronoUnit.MILLIS).toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.664
etc.
等等。