I am trying to get current time in other time zone. I used this code for this:
GregorianCalendar calender = new
GregorianCalendar(TimeZone.getTimeZone("Asia/Bangkok"));
System.out.println(calender.getTime());
But, when I am running this code, this code provides the current time in CET as the time in my local machine is in CET. I am confused. Then why there is scope to provide a TimeZone in constructor?
GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar system used by most of the world.
getGregorianChange() is an inbuilt method in Java which returns the Gregorian Calendar change date which is the change from Julian Calendar dates to Gregorian Calendar dates.
Calendar 's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time: Calendar rightNow = Calendar.
Ahh, the joys of the Java Date/Time API ...
What you want (aside from a better API, such as Joda Time) is a DateFormat
. It can print dates in a time zone you specify. You don't need Calendar
for that.
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Bangkok"));
dateFormat.format(new Date());
Calendar
is for time manipulations and calculations. For example "set the time to 10 AM". Then it needs the timezone.
When you are done with these calculations, then you can get the result by calling calendar.getTime()
which returns a Date
.
A Date
is essentially a universal timestamp (in milliseconds since 1970, with no timezone information attached or relevant). If you call toString
on a Date
it will just print something in your default timezone. For more control, use DateFormat
.
What you are doing right now is:
Date.toString()
)You should use a Formatter class to get the result you want. e.g. SimpleDateFormat
An alternative solution would be to use a less confusing Date/Time library. e.g. JodaTime or the new java.time package of Java8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With