You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript将Google Maps API返回的时区转为GMT格式字符串?

刚好做过类似的需求,给你分享几种常用编程语言的实现方法,都是经过验证可以直接用的:

JavaScript实现

如果是在浏览器或者Node.js环境下,可以用Intl.DateTimeFormat API来指定时区并提取偏移,处理成你要的格式:

function convertTimeZoneToGMT(timeZone) {
  // 创建指定时区的格式化器
  const formatter = new Intl.DateTimeFormat('en-US', {
    timeZone: timeZone,
    timeZoneName: 'longOffset'
  });
  // 解析格式化后的时间部分,提取时区偏移
  const parts = formatter.formatToParts(new Date());
  const offsetPart = parts.find(part => part.type === 'timeZoneName');
  
  // 处理偏移字符串,统一补零和格式
  let offsetStr = offsetPart.value.replace('GMT', '').trim();
  if (!offsetStr.includes(':')) {
    const sign = offsetStr.startsWith('+') ? '+' : '-';
    const num = offsetStr.replace(sign, '');
    offsetStr = `${sign}${num.padStart(2, '0')}:00`;
  } else {
    const [sign, rest] = offsetStr.startsWith('+') ? ['+', offsetStr.slice(1)] : ['-', offsetStr.slice(1)];
    const [hours, minutes] = rest.split(':');
    offsetStr = `${sign}${hours.padStart(2, '0')}:${minutes.padStart(2, '0')}`;
  }
  
  return `GMT ${offsetStr}`;
}

// 测试调用
console.log(convertTimeZoneToGMT('Asia/Damascus')); // 输出类似 GMT +03:00
Python实现

Python 3.9+可以用内置的zoneinfo模块,旧版本可以用pytz库:

基于zoneinfo(Python3.9+)

from zoneinfo import ZoneInfo
from datetime import datetime

def convert_timezone_to_gmt(timezone_str):
    tz = ZoneInfo(timezone_str)
    # 获取当前时间在目标时区的偏移(考虑夏令时)
    dt = datetime.now(tz)
    offset = dt.utcoffset()
    total_seconds = offset.total_seconds()
    
    sign = '+' if total_seconds >= 0 else '-'
    hours = int(abs(total_seconds) // 3600)
    minutes = int((abs(total_seconds) % 3600) // 60)
    
    return f"GMT {sign}{hours:02d}:{minutes:02d}"

# 测试
print(convert_timezone_to_gmt('Asia/Damascus'))

忽略夏令时(获取标准偏移)

如果不需要夏令时的动态调整,只想获取时区的标准偏移:

from zoneinfo import ZoneInfo
from datetime import datetime, timezone

def convert_timezone_to_gmt_standard(timezone_str):
    tz = ZoneInfo(timezone_str)
    rules = tz.rules
    # 获取当前时刻的标准偏移(不考虑夏令时)
    standard_offset = rules.get_standard_offset(datetime.now(timezone.utc).timestamp())
    total_seconds = standard_offset.total_seconds()
    
    sign = '+' if total_seconds >= 0 else '-'
    hours = int(abs(total_seconds) // 3600)
    minutes = int((abs(total_seconds) % 3600) // 60)
    
    return f"GMT {sign}{hours:02d}:{minutes:02d}"
Java实现

Java 8及以上可以用java.time包(JSR-310)来实现,非常简洁:

import java.time.ZoneId;
import java.time.ZonedDateTime;

public class TimeZoneConverter {
    public static String convertToGMT(String timeZoneStr) {
        ZoneId zoneId = ZoneId.of(timeZoneStr);
        ZonedDateTime zdt = ZonedDateTime.now(zoneId);
        // 获取偏移量,Z代表UTC+00:00,替换成标准格式
        String offset = zdt.getOffset().getId().replace("Z", "+00:00");
        return "GMT " + offset;
    }

    public static void main(String[] args) {
        // 测试调用
        System.out.println(convertToGMT("Asia/Damascus"));
    }
}

注意:所有默认实现都会考虑夏令时的影响,返回当前时间对应的偏移;如果需要固定偏移,参考Python里的标准偏移获取方法,其他语言也可以通过时区规则获取标准偏移量。

内容的提问来源于stack exchange,提问作者Nir Ben-Yair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 02:30:19