yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z' format

佐手、 提交于 2019-12-25 09:39:24

问题


I am trying to convert GMT to IST.

  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS");
  Date c= sdf.parse("2017-03-31T10:38:14.4723017Z");

  Date date = new Date();
  DateFormat istFormat = new SimpleDateFormat();
  DateFormat gmtFormat = new SimpleDateFormat();
  TimeZone gmtTime = TimeZone.getTimeZone("GMT");
  TimeZone istTime = TimeZone.getTimeZone("IST");

  istFormat.setTimeZone(gmtTime);
  gmtFormat.setTimeZone(istTime);
  System.out.println("GMT Time: " + istFormat.format(c));
  System.out.println("IST Time: " + gmtFormat.format(c));

My output is

GMT Time: 31/3/17 6:26 AM
IST Time: 31/3/17 11:56 AM

But my actual output should be

GMT Time: 31/3/17 5:08 AM
IST Time: 31/3/17 10:38 AM

What is wrong with my code?


回答1:


Milliseconds (SSS) can only be three digits. On more than that, the date rolls over - e.g. 10:38:14.1000 becomes 10:38:15.000. Add a couple of million milliseconds... and you get the behaviour that you're seeing now.

Try this.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date c = sdf.parse("2017-03-31T10:38:14.472Z");

System.out.println(c);

DateFormat istFormat = new SimpleDateFormat();
DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
TimeZone istTime = TimeZone.getTimeZone("IST");

istFormat.setTimeZone(gmtTime);
gmtFormat.setTimeZone(istTime);
System.out.println("GMT Time: " + istFormat.format(c));
System.out.println("IST Time: " + gmtFormat.format(c));



回答2:


Have you tried changing the format to "yyyy-MM-dd'T'HH:mm:ss.sssssssZ"?

Also, when you type Z in your Date object, you should write the time zone designator, for example, "2017-03-31T10:38:14.4723017+01:00".



来源:https://stackoverflow.com/questions/44000755/yyyy-mm-ddthhmmss-sssssssz-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!