0

I am trying to print the current date in GMT Format but it is getting only in IST format.

public static void main(String[] args) throws ParseException { 
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss zzz");

    Date date = new Date();
    System.out.println("Local Time: " + sdf.format(date));

    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    System.out.println("GMT Time  : " + sdf.format(date));
    Date date1=new SimpleDateFormat("yyyy MMM dd HH:mm:ss zzz").parse(sdf.format(date));  
    System.out.println("\t"+date1); 
}

This is my output

Local Time: 2019 Apr 08 19:48:23 IST GMT Time : 2019 Apr 08 14:18:23 GMT Mon Apr 08 19:48:23 IST 2019

but i want to like this 2019 Apr 08 14:18:23 GMT after parsing the string to date.

Jackson
  • 5,627
  • 2
  • 29
  • 48
niteesh
  • 39
  • 1
  • 1
  • 9
  • 1
    https://stackoverflow.com/questions/24533484/how-to-convert-java-util-date-to-gmt-format – Mr. Arbitrary Apr 08 '19 at 14:26
  • Why are you using `Date` and `SimpleDateFormat`? Why not use `java.time` classes? These are obsolete. – RealSkeptic Apr 08 '19 at 14:29
  • @LppEdd read clearly my question.. in this line `Date date1=new SimpleDateFormat("yyyy MMM dd HH:mm:ss zzz").parse(sdf.format(date));` it is not getting GMT – niteesh Apr 08 '19 at 14:32
  • @RealSkeptic can you show me example please – niteesh Apr 08 '19 at 14:33
  • @niteesh look at https://stackoverflow.com/questions/18122608/simpledateformat-parse-loses-timezone You need to use `setTimeZone` – LppEdd Apr 08 '19 at 14:48
  • I'd ask a moderator to "swap" the currently choosen duplicate with the above one – LppEdd Apr 08 '19 at 14:49
  • Your second print seems correct, so it's not very clear what problem you are having. Note that a `java.util.Date` does *not* contain a timezone, so parsing to one will lose you that information. The `toString` output is misleading and should not be used (and neither should the class itself, really). – TiiJ7 Apr 08 '19 at 14:52

0 Answers0