简体   繁体   中英

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

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?

Milliseconds (SSS) can only be three digits. On more than that, the date rolls over - eg 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));

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".

尝试使用这种格式“yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM