Calendar.getInstance().getTime() returning date in “GMT” instead of Default TimeZone

后端 未结 3 748
温柔的废话
温柔的废话 2021-01-19 13:16
Calendar c = Calendar.getInstance();
System.out.println(c.getTime());
c.set(2007, 0, 1);
System.out.println(c.getTime());

Output:

3条回答
  •  逝去的感伤
    2021-01-19 14:06

    You need to set time zone and you will get desired result.

    TimeZone.setDefault(TimeZone.getTimeZone("IST"));

    Here is a working code.

    import java.util.Calendar;
    import java.util.TimeZone;  
    public class Cal {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            TimeZone.setDefault(TimeZone.getTimeZone("IST")); // Add this before print
            Calendar c = Calendar.getInstance();    
            System.out.println(c.getTime());
            c.set(2007, 0, 1);
            System.out.println(c.getTime());
        }
    
    }
    

    As per Doc "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."

    SO when you running in different timezone it is using as default timezone. Hope you clear now. I attach doc. please read.

提交回复
热议问题