public static String timeZone(Date date,ZoneId zoneId) throws ParseException { //先得出世界时间 LocalDateTime UTCTime = LocalDateTime.ofInstant(date.toInstant(), TimeZone.getTimeZone("UTC").toZoneId()); LocalDateTime GBTIme = LocalDateTime.ofInstant(date.toInstant(), zoneId); System.out.println(UTCTime); System.out.println(GBTIme); Long utc = UTCTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); Long gb = GBTIme.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); System.out.println(date.getTime() - gb); System.out.println(date.getTime() - utc); System.out.println(utc); System.out.println(gb); //计算时间差 if (UTCTime.compareTo(GBTIme) > 0) { Long gmt = (utc - gb) / 1000 / 60 / 60; return "GMT-" + gmt.toString() + ":00"; } else { Long gmt = (gb - utc ) / 1000 / 60 / 60; return "GMT+" + gmt.toString() + ":00"; } } public static void main(String[] args) { try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("CN")); Date date = dateFormat.parse("2023-04-02 01:00:00"); System.out.println(timeZone(date, TimeZone.getTimeZone("Europe/London").toZoneId())); } catch (ParseException e) { e.printStackTrace(); } } //这个办法更好 public static void main(String[] args) { // 设置默认时区为美国纽约 TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); // 获取当前默认时区 TimeZone timeZone = TimeZone.getDefault(); // 输出时区信息 System.out.println("地区: " + timeZone.getDisplayName()); System.out.println("时区ID: " + timeZone.getID()); System.out.println("时区偏移量: " + timeZone.getRawOffset() / (60 * 60 * 1000) + " 小时"); }
给定一个时间,求出当地时区
Java 根据时间与地区查出当地时区
于 2023-03-29 14:58:06 首次发布