0
Date date = new Date();
DateFormat format = new SimpleDateFormat("dd/MM/yy h:mm a zzz");
format.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String currentTimeInEST = format.format(date);

The above code gets me the current time in the required timezone. However, I am not able to convert currentTimeInEST back to Date object and print the date and time in EST. It is getting converted to default time zone. I could not find any possible ways in any forum.

Florent Bayle
  • 11,520
  • 4
  • 34
  • 47
  • What are you using for the backwards conversion? `format.parse(currentTimeInEST);`? – Boris Strandjev Dec 30 '14 at 10:31
  • The above code does print the date in the new york timezone. That's what you need to use to print a Date, which doesn't have any time zone, in a given time zone. Date.toString() does basically the same thing as the above code, but uses the default time zone rather than New York. – JB Nizet Dec 30 '14 at 10:32
  • @BorisStrandjev, yes I used the same. But it is printing in the default time zone and not in EST. – PlanetSaro Dec 30 '14 at 10:36
  • We are not speaking of printing here - with this method you construct a date object, then it is again up to you to format it accordingly. What happens when you do: `System.out.println(format.format(format.parse(currentTimeInEST)));` – Boris Strandjev Dec 30 '14 at 10:37
  • @BorisStrandjev, I am sorry. I was printing the output in the console and hence used 'printing'. The code above, gives the result in EST as expected. Formatting the Date objects works fine. But constructing a Date object from EST String is not working as expected. – PlanetSaro Dec 30 '14 at 10:41
  • How do you construct it then? – Boris Strandjev Dec 30 '14 at 10:57
  • 1
    @PlanetSaro I repeat: a Date object is just a number of milliseconds. It doesn't have any time zone. When you transform this number of milliseconds to a String, then you choose which timezone to use. Date.toString() chooses to use the default timezone. If you want another, then use the code in your question. – JB Nizet Dec 30 '14 at 11:06
  • Take a look at this answer I wrote in another similar question about Dates and Strings. I think it may be helpful: http://stackoverflow.com/questions/26672773/format-a-date-string-java/26678815#26678815 – Tobías Dec 30 '14 at 11:12
  • @BorisStrandjev, I used format.parse(currentTimeInEST) to convert it to Date Object.
    – PlanetSaro Dec 30 '14 at 11:15
  • And apaprently this works as expected looking at the experiment above. Maybe you get confused, by the fact that with all these manipulations you do not modify the default format to use with the new date, thus the timezone is also the default. – Boris Strandjev Dec 30 '14 at 11:18
  • Yes, I understood it now. I used Calendar Object to convert currentTimeInEST back to Date and get the proper data. Thank you JB Nizet and BorisStrandjev. Your help is appreciated. – PlanetSaro Dec 31 '14 at 06:12

0 Answers0