How to set Z as timezone in SimpleDateFormat

前端 未结 2 441
独厮守ぢ
独厮守ぢ 2021-01-29 12:42

Code sample:

SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss z\");
System.out.println(dateFormat.getTimeZone());
System.out.println(dat         


        
2条回答
  •  广开言路
    2021-01-29 13:20

        DateTimeFormatter formatter 
                = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss z", Locale.ENGLISH);
        String time ="2018-04-06 16:13:00 IST";
        ZonedDateTime dateTime = ZonedDateTime.parse(time, formatter);
        System.out.println(dateTime.getZone());
    

    On my Java 8 this printed

    Asia/Jerusalem

    So apparently IST was interpreted as Israel Standard Time. On other computers with other settings you will instead get for instance Europe/Dublin for Irish Summer Time or Asia/Kolkata for India Standard Time. In any case the time zone comes from the abbreviation matching the pattern letter (lowercase) z in the format pattern string, which I suppose was what you meant(?)

    If you want to control the choice of time zone in the all too frequent case of ambiguity, you may build your formatter in this way (idea stolen from this answer):

        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendPattern("uuuu-MM-dd HH:mm:ss ")
                .appendZoneText(TextStyle.SHORT,
                        Collections.singleton(ZoneId.of("Asia/Kolkata")))
                .toFormatter(Locale.ENGLISH);
    

    Now the output is

    Asia/Kolkata

    I am using and recommending java.time over the long outdated and notoriously troublesome SimpleDateFormat class.

    Link: Oracle tutorial: Date Time explaining how to use java.time.

提交回复
热议问题