Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GregorianCalendar Class in Java

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?

like image 984
Srijani Ghosh Avatar asked Feb 03 '15 10:02

Srijani Ghosh


People also ask

What is Gregorian calendar in Java?

GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar system used by most of the world.

What is the return type for the getGregorianChange () method?

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.

What is the use of calendar getInstance () in Java?

Calendar 's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time: Calendar rightNow = Calendar.


2 Answers

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.

like image 183
Thilo Avatar answered Sep 25 '22 07:09

Thilo


What you are doing right now is:

  • Getting a calendar in Bangkok time zone
  • get the Date object for this time( which is in ms since some date January 1, 1970, 00:00:00 GMT)
  • print out this Date in your timezone (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

like image 26
Dawnkeeper Avatar answered Sep 23 '22 07:09

Dawnkeeper