为什么Java日期不可解析? [英] Why java date is not parsable?

查看:89
本文介绍了为什么Java日期不可解析?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用oracle MAF开发移动应用程序. Oracle MAF提供了其日期组件,如果我选择一个日期,则输出类似于:2015-06-16T04:35:00.000Z表示所选日期Jun 16, 2015 10:05 AM.

I am developing a mobile application using oracle MAF. Oracle MAF provides its date component and if I select a date then output is like : 2015-06-16T04:35:00.000Z for selected date Jun 16, 2015 10:05 AM.

我正在尝试将此格式转换为.ical(ICalendar日期格式)的印度标准时间",对于所选日期Jun 16, 2015 10:05 AM,该格式应类似于20150613T100500.我在下面使用代码:

I am trying to convert this format to "Indian Standard Time" with .ical (ICalendar Date format) which should be like 20150613T100500 for the selected date Jun 16, 2015 10:05 AM. I am using code below:

SimpleDateFormat isoFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
isoFormat.setTimeZone(TimeZone.getTimeZone("IST"));
String start_date_time = isoFormat.parse("20150616T043500000Z").toString();

但是它返回日期时间为:

But it returns date time as :

Tue Jun 16 04:35:00 GMT+5:30 2015

并且应该像这样:

20150616T100500

推荐答案

您需要将值从2015-06-16T04:35:00.000Z UTC解析为java.util.Date

You need to parse the value from 2015-06-16T04:35:00.000Z UTC to a java.util.Date

SimpleDateFormat from = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
from.setTimeZone(TimeZone.getTimeZone("UTC"));
Date start_date_time = from.parse("2015-06-16T04:35:00.000Z");

哪个给了我们Tue Jun 16 14:35:00 EST 2015java.util.Date(对我来说).

Which gives us a java.util.Date of Tue Jun 16 14:35:00 EST 2015 (for me).

然后,您需要在IST中对其进行格式化

Then, you need to format this in IST

SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
outFormat.setTimeZone(TimeZone.getTimeZone("IST"));
String formatted = outFormat.format(start_date_time);
System.out.println(formatted);

哪个输出20150616T100500

只是因为这是一个好习惯...

Just because it's good practice...

    // No Time Zone
    String from = "2015-06-16T04:35:00.000Z";
    LocalDateTime ldt = LocalDateTime.parse(from, DateTimeFormatter.ISO_ZONED_DATE_TIME);
    
    // Convert it to UTC
    ZonedDateTime zdtUTC = ZonedDateTime.of(ldt, ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("UTC"));

    // Convert it to IST
    ZonedDateTime zdtITC = zdtUTC.withZoneSameInstant(ZoneId.of("Indian/Cocos"));
    String timestamp = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss").format(zdtITC);
    System.out.println(timestamp);

nb:如果我没有将值解析为LocalDateTime,然后将其转换为UTC,我已经缺席了一个小时,但我愿意了解更好的方法

nb: If I didn't parse the value to LocalDateTime, then convert it to UTC, I was out by an hour, but I'm open to knowing better ways

这篇关于为什么Java日期不可解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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