Java How to get time printed in IST

后端 未结 2 1323
长情又很酷
长情又很酷 2020-12-19 17:27

I am able to get the time as well as timezone currently. but it always printed in

Wed May 23 11:01:08 GMT+05:30 2012

As TimeZone i am gett

相关标签:
2条回答
  • 2020-12-19 17:32

    Seems you have a wrong timezone setting. The following code will print 2012.05.23 AD at 11:30:20 IST

    TimeZone.setDefault(TimeZone.getTimeZone("IST"));
    SimpleDateFormat f = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
    System.out.println(f.format(new Date()));
    

    However, if I use TimeZone.setDefault(TimeZone.getTimeZone("GMT+05:30"));

    I'll get 2012.05.23 AD at 11:30:20 GMT+05:30.

    What comes in, comes out identical.

    0 讨论(0)
  • 2020-12-19 17:34

    You haven't shown where you're actually using the SimpleDateFormat. Here's a short but complete example which does show IST:

    import java.text.*;
    import java.util.*;
    
    class Test {
        public static void main(String[] args) {
            SimpleDateFormat sd = new SimpleDateFormat(
                "yyyy.MM.dd G 'at' HH:mm:ss z");
            Date date = new Date();
            // TODO: Avoid using the abbreviations when fetching time zones.
            // Use the full Olson zone ID instead.
            sd.setTimeZone(TimeZone.getTimeZone("IST"));
            System.out.println(sd.format(date));
       }
    }
    

    Output on my machine:

    2012.05.23 AD at 11:18:08 IST
    

    Note that if TimeZone.getDefault() isn't showing "IST" then the issue may be:

    • That the system can't actually identify your system time zone
    • That your Java installation doesn't have full time zone information regarding i18n

    Which version of Java are you using, and on what platform?

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