123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- package com.szwl.util;
- import java.time.ZoneId;
- import java.time.ZonedDateTime;
- import java.time.format.DateTimeFormatter;
- public class TimezoneFmtUtil {
- public static void main(String[] args) {
- // String timeZoneByID = getTimeByZoneID("Asia/Shanghai"); // America/New_York, Asia/Shanghai
- // System.out.println(timeZoneByID);
- // String nowDateUTC = getNowDateUTC();
- // System.out.println("nowDateUTC >>> " + nowDateUTC);
- }
- /**
- * 获取 zoneID 时区的时间
- *
- */
- public static String getTimeByZoneID(String zoneID) {
- String formatted = null;
- if (ZoneId.getAvailableZoneIds().contains(zoneID)) {
- ZoneId zoneId = ZoneId.of(zoneID);
- ZonedDateTime now = ZonedDateTime.now(zoneId);
- DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss 'UTC'xxx");
- formatted = now.format(dateTimeFormatter);
- } else {
- System.out.println("zoneID有误!");
- }
- return formatted;
- }
- /**
- * 获取中国时区的UTC格式
- *
- */
- // public static String getNowDateUTC() {
- // ZoneId zoneId = ZoneId.of("Asia/Shanghai");
- // ZonedDateTime now = ZonedDateTime.now(zoneId);
- // DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss 'UTC'xxx");
- // return now.format(dateTimeFormatter);
- // }
- // public static String getTimeZoneByID(String timeZoneID) {
- // // 获取时区对象
- // TimeZone timeZone = TimeZone.getTimeZone(timeZoneID);
- //
- // // 设置时区
- // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- // sdf.setTimeZone(timeZone);
- //
- // // 获取当前时间
- // Calendar calendar = Calendar.getInstance();
- // calendar.setTimeZone(timeZone);
- // Date date = calendar.getTime();
- //// String displayName = timeZone.getDisplayName();
- //
- // // 计算UTC偏移量
- // int rawOffset = timeZone.getRawOffset();
- // int rawOffsetHours = rawOffset / (1000 * 60 * 60);
- //
- // int hours = 0;
- //// String formatted = null;
- // if (ZoneId.getAvailableZoneIds().contains(timeZoneID)) {
- // ZoneId zoneId = ZoneId.of(timeZoneID);
- //
- //// ZonedDateTime now = ZonedDateTime.now(zoneId);
- //// DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss 'UTC'xxx");
- //// formatted = now.format(dateTimeFormatter);
- //
- //
- // ZoneOffset offset = zoneId.getRules().getOffset(Instant.now()); // 获取当前时刻的偏移量
- // int totalSeconds = offset.getTotalSeconds();
- // hours = totalSeconds / (60 * 60);
- // } else {
- // System.out.println("zoneID有误!");
- // }
- //
- // return sdf.format(date) + " UTC " + hours;
- //// return formatted;
- // }
- }
|