Java 根据时间与地区查出当地时区

    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) + " 小时");
    }

给定一个时间,求出当地时区

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值