我正在寻找的正确日期格式:-“2017-07-06T18:03:39.195+0530”
如何在java中获取当前日期的+0530?
当我使用 SimpleDateFormat 时,它给出 +0000 ,而它应该给出 +0530 。
=====================================================
我已尝试使用以下:-
SimpleDateFormat format = new SimpleDateFormat("enter code hereyyy-MM-dd HH:mm:ss.SSS Z");
String dateString = format.format(new Date());
System.out.println("value of dateString is :"+dateString);
Run Code Online (Sandbox Code Playgroud)
上面的代码将输出:- dateString 的值为:2017-07-10 06:51:27.250 +0000
而它应该输出:+0530
您能告诉我如何获得上述日期或当前日期的 +0530 偏移量吗?
ZonedDateTime.now( ZoneId.of( "Asia/Kolkata" ) ).toOffsetDateTime().toString()\nRun Code Online (Sandbox Code Playgroud)\n\nOffsetDateTime要直接解决问题,请使用现代OffsetDateTime类。
OffsetDateTime.now().toString()\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n\n\n\nodt.toString(): 2019-08-22T17:44:00.219684Z
\n
这将使用标准ISO 8601格式生成一个字符串,表示 JVM\xe2\x80\x99s 当前默认时区使用的偏移量中的当前时刻。一个区别:此方法将:在偏移量的小时和分钟之间包含可选的冒号字符。我建议永远不要省略该字符,因为我已经看到多个库在此类输入上中断,期望冒号在那里。
捕获当前时刻时,结果可能会解析为微秒。如果您更喜欢毫秒,请截断,去掉微秒。
\n\nOffsetDateTime.now().truncatedTo( ChronoUnit.MILLIS ) \nRun Code Online (Sandbox Code Playgroud)\n\n\n\n\nodtTruncated.toString(): 2019-08-22T17:44:00.219Z
\n
在 IdeOne.com 上运行的代码位于 JVM 中,其中对于 UTC 本身,偏移量设置为零。Z因此,我们在末尾看到,它是 的常见且标准的替代方案+00:00,发音为 \xe2\x80\x9cZulu\xe2\x80\x9d。
您可能想明确指定您的偏移量。
\n\nInstant instant = Instant.now() ; // Current moment in UTC.\nZoneOffset offset = ZoneId.of( "Asia/Kolkata" ).getRules().getOffset( instant ) ; // We must pass a moment. India is currently at five and a half hours ahead of UTC. But it has not always been so in the past, and may not always be so in the future.\nOffsetDateTime odt = instant.atOffset( offset ) ;\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n\nodt.toString(): 2019-08-22T23:00:06.925139+05:30
\n
我认为更清晰的语法是使用ZonedDateTime.
String output = ZonedDateTime.now( ZoneId.of( "Asia/Kolkata" ) ).toOffsetDateTime().toString() ;\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n\n2019-08-22T23:03:19.072681+05:30
\n
ZonedDateTime更有可能的是,您应该获取时区的当前时刻,而不仅仅是偏移量。如果是这样,请参阅RaT 的答案。
\n\n明确偏移量和区域之间的区别:
\n\nContinent/Region,例如America/Montreal或Africa/Tunis。通常,您应该避免使用糟糕的日期时间类,例如现在已遗留的java.util.Date和。SimpleDateFormat始终使用Instant、OffsetDateTime和ZonedDateTime。切勿使用Date& Calendar。
但是,如果您必须在与尚未更新的java.time类的旧代码进行互操作时必须使用旧类,则可以来回转换。RaT 的答案中显示了这一点。
\n\n
| 归档时间: |
|
| 查看次数: |
9419 次 |
| 最近记录: |