集册 Java实例教程 Java打印时区ID,用于由一小时以外的时间偏移的时区

Java打印时区ID,用于由一小时以外的时间偏移的时区

欢马劈雪     最近更新时间:2020-01-02 10:19:05

602
Java打印时区ID,用于由一小时以外的时间偏移的时区
/** from 
时代Java公众号 - nowjava.com**/

import java.util.Set;

import java.util.List;

import java.util.Collections;

import java.util.ArrayList;


import java.time.ZoneId;

import java.time.ZoneOffset;

import java.time.ZonedDateTime;

import java.time.LocalDateTime;


import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.Files;

import java.nio.charset.StandardCharsets;

import java.io.BufferedWriter;

import java.io.PrintStream;

import java.io.IOException;


/*

 * This program performs two functions:

 *   1. It prints, to standard out, a list of time zone IDs for time zones

 *      that are offset by times other than an hour.

 *   2. It prints a file, called "timeZones", that contains a list of

 *      all time zone IDs.

 *///from 时 代      J a v a   公   众 号 - nowjava.com


public class TimeZoneId {

    public static void main(String[] args) {


        // Get the set of all time zone IDs.

        Set<String> allZones = ZoneId.getAvailableZoneIds();


        // Create a List using the set of zones and sort it.

        List<String> zoneList = new ArrayList<String>(allZones);

        Collections.sort(zoneList);


        LocalDateTime dt = LocalDateTime.now();


        Path p = Paths.get("timeZones");

        try (BufferedWriter tzfile = Files.newBufferedWriter(p,

                StandardCharsets.US_ASCII)) {

            for (String s : zoneList) {

                ZoneId zone = ZoneId.of(s);

                ZonedDateTime zdt = dt.atZone(zone);

                ZoneOffset offset = zdt.getOffset();

                int secondsOfHour = offset.getTotalSeconds() % (60 * 60);

                String out = String.format("%35s %10s%n", zone, offset);


                // Write only time zones that do not have a whole hour offset

                // to standard out.

                if (secondsOfHour != 0) {

                    System.out.printf(out);

                }


                // Write all time zones to the file.

                tzfile.write(out);

            }

        } catch (IOException x) {

            System.err.format("IOException: %s%n", x);

        }

    }

}


展开阅读全文