I need to convert from one timezone to another timezone in my project.
I am able to convert from my current timezone to another but not from a different timezone to another.
For example I am in India, and I am able to convert from India to US using Date d=new Date();
and assigning it to a calendar object and setting the time zone.
However, I cannot do this from different timezone to another timezone. For example, I am in India, but I am having trouble converting timezones from the US to the UK.
If you don't want to use Joda, here is a deterministic way using the built in libraries.
First off I recommend that you force your JVM to default to a timezone. This addresses the issues you might run into as you move your JVM from one machine to another that are set to different timezones but your source data is always a particular timezone. For example, lets say your data is always PDT/PST time zone, but you run on a box that is set to UTC timezone.
The following code snippet sets the default timezone in my JVM:
Now lets say your source date is coming in as PDT/PST but you need to convert it to UTC. These are the steps:
The output would be:
Some examples
Convert time between timezone
Converting Times Between Time Zones
You can use the following code snippet
The "default" time zone can be avoided entirely by just setting the time zone appropriately for the
Calendar
object. However, I would personally suggest that you use Joda Time as a far superior API for date and time operations in Java. Amongst other things, time zone conversion is very simple in Joda.It's not clear what your current code looks like and why you're only able to convert via the default time zone, but in Joda Time you'd just specify the time zone explicitly when creating (say) a
DateTime
object, and then usewithZone(DateTimeZone zone)
.If you could tell us more about how you're getting input data, we could give a fuller example.