代码示例:
// 给定的GMT时间串 String gmtTimeStr = "2023/12/13 16:58:00"; // 创建SimpleDateFormat对象,定义输入格式 SimpleDateFormat gmtFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); gmtFormat.setTimeZone(TimeZone.getTimeZone("GMT")); try { // 将GMT时间字符串解析为Date对象 Date gmtTime = gmtFormat.parse(gmtTimeStr); // 获取本地时区 TimeZone localTimeZone = TimeZone.getDefault(); // 创建SimpleDateFormat对象,定义输出格式,并设置时区为本地时区 SimpleDateFormat localFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); localFormat.setTimeZone(localTimeZone); // 将GMT时间转换为本地时间 String localTimeStr = localFormat.format(gmtTime); // 输出本地时间 System.out.println("GMT时间: " + gmtTimeStr); System.out.println("本地时间: " + localTimeStr); } catch (ParseException e) { e.printStackTrace(); }
注意 SimpleDateFormat设置时区从字符串转时间,字符串时间不会变化,从时间转字串,时间会相应的改变。
对象的模式被设置为 "yyyy/MM/dd HH:mm:ss",这意味着它期望输入和输出的日期和时间字符串是这种格式的。