如何在Java中以ISO日期格式打印当前时间和日期? [英] How to print the current time and date in ISO date format in java?

查看:216
本文介绍了如何在Java中以ISO日期格式打印当前时间和日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该按照下面给出的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'

我写了以下代码:

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));

它以以下方式打印:

2018-04-30T12:02
2018-04-30T12:02:58.000Z

但是它不是按照上述格式打印的.如何获取格式所示的-5:00,它表示什么?

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?

推荐答案

在Java 8中,您可以使用新的

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


以上使用标准的ISO数据时间格式器.您还可以使用以下方法截断毫秒数:


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

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

会产生类似的结果(点后仅3位数字):

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

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

这篇关于如何在Java中以ISO日期格式打印当前时间和日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆