What is the default timezone for java.util.Calendar.?

后端 未结 4 1000
一整个雨季
一整个雨季 2021-02-09 16:26

Code

public String testDate(){ 
      TimeZone.setDefault(TimeZone.getTimeZone(\"US/Eastern\"));
      Calendar fromDate = Calendar.getInstance(         


        
相关标签:
4条回答
  • 2021-02-09 16:49

    The date itself doesn't have any time zone. It's toString() method uses the current default time zone to return a String

    0 讨论(0)
  • 2021-02-09 17:10

    According to Oracle Documentation it is clearly mentioned that,

    public static Calendar getInstance()
    Gets a calendar using the default time zone and locale. The Calendar returned is based on the current time in the default time zone with the default locale.

    And the default time zone is got by public static TimeZone getDefault() and it is mentioned in TimeZone.getDefault() that

    Gets the default TimeZone for this host. The source of the default TimeZone may vary with implementation.

    It will return the default timezone set in your computer until and unless you have used public static void setDefault(TimeZone zone) function to set the TimeZone explicitly.

    I believe the above explanation answers your both the question,

    1. What is the default timezone of java.util.Calendar.?
    2. Why is my variable cal of type Calendar shows a time that is not IST or EST.?

    EDIT: As per your edited question

    Why is cal of Calendar and date of Date() different?

    When you call System.out.println(date); then toString() function is invoked and if you look at Source Code of Date you will find that it returns 3 letters shorthand for timezone by invoking the displayName function of default time zone which is 3 letters shorthand in your case EST, which is U.S. Eastern Standard Time (GMT-05:00) Indiana (East).

    0 讨论(0)
  • 2021-02-09 17:11

    Typically, you get a TimeZone using getDefault which creates a TimeZone based on the time zone where the program is running. For example, for a program running in Japan, getDefault creates a TimeZone object based on Japanese Standard Time.

    Check TimeZone for more

    0 讨论(0)
  • 2021-02-09 17:11

    You mention "cdate", and I notice there is a field inside the Calendar object called cdate. In running your sample code, I see that the cdate field is indeed initialized to 2013-12-10T00:00:00.000Z (it now being 24 hours later of course).

    So? I don't know why you are looking at internal fields of a class when you are never going to directly use them.

    Your solution, then, is to ignore it. Don't worry about the cdate field of your Calendar; worry about things that actually affect your program.

    The toString() of a Calendar is not very pretty and is intended for debugging; you should call cal.getTime() which will give you a java.util.Date that you can then print out either directly or by using a java.text.DateFormatter.

    0 讨论(0)
提交回复
热议问题