打印当前时间java格式,如何在Java中以ISO日期格式打印当前时间和日期?

I am supposed to send the current date and time in ISO format as given below:

'2018-02-09T13:30:00.000-05:00'

I have written the following code:

Date date = new Date();

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");

SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.000'Z'");

System.out.println(formatter.format(date));

System.out.println(formatter1.format(date));

It prints in the following way:

2018-04-30T12:02

2018-04-30T12:02:58.000Z

But it is not printing as the format mentioned above. How can I get the -5:00 as shown in the format and what does it indicate?

解决方案

In java 8 you can use the new java.time api:

OffsetDateTime now = OffsetDateTime.now();

DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;

System.out.println(formatter.format(now)); // e.g. 2018-04-30T08:43:41.4746758+02:00

The above uses the standard ISO data time formatter. You can also truncate to milliseconds with:

OffsetDateTime now = OffsetDateTime.now().truncatedTo(ChronoUnit.MILLIS);

Which yields something like (only 3 digits after the dot):

2018-04-30T08:54:54.238+02:00

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值