I used the following code to convert an input date string to different timezones. However, this code is working only if the input date string is in TimeZone GMT and fails to convert when it is in any other timezone. Can someone throw any light?
Class java.util.Date contains the number of milliseconds since the epoch of 01/01/1970 00:00:00.000 UTC. It contains no explicit time zone information but has an implicit time one of UTC ( effectively GMT ) . This applies no matter what time zone your computer is configured to.
When you parse a string using SimpleDateFormat to get a java.util.Date a time zone is needed. If one does not explicitly specify a time zone then the time zone of your computer is used.
When one formats a java.util.Date to a String using SimpleDateFormat a time zone is needed. If one does not explicitly specify a time zone then the time zone of your computer is used.
Retired horse trader.
Note: double-underline links may be advertisements automatically added by this site and are probably not endorsed by me.
But my code is explicitly setting the time zone to SimpleDateFormat in getDateInTimeZone() method. Can someone explain why this works only when GMT date string is used as input?
Your method, if it is to do what you claim it does, should take two time zones as parameters. The "from" time zone and the "to" time zone. As it is, you convert a string to a date using time zone X, and then convert the date back to a string using that same time zone. This basically does nothing.
Actually, I notice you used the phrase "failed to convert" in your original post. What happened instead?
One critical thing to understand is that in Java, a Date object does *NOT* have a timezone. Nothing you can do to a Date will change its timezone.
Only DateFormats have timezones. So you set the timezone you want into the DateFormat (or any class that subclasses from it). Use the DateFormat to output your Date and you will be happy.