jersey mysql_Jersey has written my mysql timestamp as 2011-09-28T21:48:25Z how do I format it in Jav...

本文介绍如何在Java中解析标准ISO8601格式的日期时间字符串,并将其转换为Java可理解的日期类型。通过使用SimpleDateFormat和Instant类进行解析,并介绍了如何调整时间区。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题

This question already has answers here:

ISO 8601 String to Date/Time object in Android

(4 answers)

Closed last year.

I have a mysql backend that has a timestamp field that is auto set as currenttimestamp like so (date_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP). After reading the value as Date, Jersey sends out an xml where the timestamp shows as

2011-09-28T21:48:25Z

Please don't make too much of the backstory: I can't change what I get from Jersey. Now my question is this: how do I parse the 2011-09-28T21:48:25Z from xml as a date that Java understands?

Thanks.

回答1:

First,

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") ;

df.setTimeZone(TimeZone.getTimeZone("Zulu")) ;

Date dd = df.parse("2011-09-28T21:48:25Z") ;

...then, optionally,

Timestamp ts = new Timestamp(dd.getTime()) ;

回答2:

tl;dr

Instant.parse( "2011-09-28T21:48:25Z" )

ISO 8601

Your input string is in standard ISO 8601 format.

Jersey is irrelevant, except that its designers wisely chose to use ISO 8601 formats for serializing date-time values as strings.

java.time

The java.time classes built into Java use ISO 8601 formats by default when parsing/generating Strings. So no need to specify a formatting pattern.

UTC

The Z on the end is short for Zulu and means UTC (GMT).

Instant

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.

Instant instant = Instant.parse( "2011-09-28T21:48:25Z" );

Time Zone

Adjust that Instant into any time zone you desire.

Specify a proper time zone name. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata" etc.

ZonedDateTime zdt = instant.atZone( z );

Strings

Do not conflate date-time values with Strings that represent such values.

You can ask the java.time objects to generate a String in any format you desire. But generally best to let the DateTimeFormatter automatically localize for you.

Locale l = Locale.CANADA_FRENCH; // Or Locale.US, Locale.ITALY, etc.

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );

String output = zdt.format( f );

来源:https://stackoverflow.com/questions/7604237/jersey-has-written-my-mysql-timestamp-as-2011-09-28t214825z-how-do-i-format-it

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值