java define的格式,在java中我需要以这种格式定义日期1999-05-31T13:20:00-05:00

I need to define date in this format 1999-05-31T13:20:00-05:00

I am using below code

SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD'T'hh:mm:ssZ");

sdf.setTimeZone(TimeZone.getTimeZone("EST"));

String date = sdf.format(new Date());

System.out.println(date);

but it is generating date in format 2017-04-117T08:28:46-0500 (missing semicolon in timezone)

After defining the date I have to create an instance of XMLGregorianCalendar with same date.

解决方案

I was surprised you didn’t find the answer when searching for it. Anyway, it’s easy. Two words of caution first, though:

Skip the three-letter time zone abbreviations. Many are ambiguous. While I think EST only means Eastern Standard Time, this isn’t a full time zone, since (most of?) that zone is on EDT now, which does not make it very clear what result you want.

If there’s any way you can, skip the old-fashioned classes SimpleDateFormat, TimeZone and Date. The new classes in java.time are generally much nicer to work with.

The format you are asking for is exactly what DateTimeFormatter.ISO_OFFSET_DATE_TIME is giving you. If you meant to have the time formatted suitably for a user in the Eastern time zone, use:

ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/New_York"))

.truncatedTo(ChronoUnit.SECONDS);

System.out.println(now.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));

Note the use of the unambiguous time zone ID and of the mentioned formatter. The format will print milliseconds (and even smaller) if there are any, which you didn’t ask for. So I have cheated a bit: I am truncating the time to whole seconds. Now this prints something like:

2017-04-27T10:11:33-04:00

If instead you wanted the offset -05:00, that’s even easier:

OffsetDateTime now = OffsetDateTime.now(ZoneOffset.ofHours(-5))

.truncatedTo(ChronoUnit.SECONDS);

System.out.println(now);

This prints something in the same format, but with the desired offset:

2017-04-27T09:11:33-05:00

The toString method of OffsetDateTime gives you the format you want. Of course, if you prefer, you can use the same formatter as before.

If truncating to seconds is a bit too much cheating for your taste, you may of course use a formatter without milliseconds:

DateTimeFormatter isoNoSeconds = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX");

System.out.println(now.format(isoNoSeconds));

This will work with both a ZonedDateTime and an OffsetDateTime, that is, with both of the above snippets.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值