格林威治时间加上8h即为北京时间
本文以格林威治时间转为北京时间为例,若需将北京时间转为格林威治时间只需将文中+8改为-8即可
1. 时间格式为:2021-01-04T04:16:23.609Z
此处T为分隔符,Z为时区
package org.example;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
//时间格式为:2021-01-04T22:15:06.714Z
public class Time {
public static void test(String date) throws ParseException {
//设置时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
//将输入时间转换为ms
sdf.parse(date).getTime();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(sdf.parse(date).getTime());
System.out.println("格林威治时间:" + cal.getTime());
cal.add(Calendar.HOUR, +8);
System.out.println("北京时间:" + cal.getTime());
}
public static void main(String[] args) throws ParseException {
test("2021-01-04T04:16:23.609Z");
}
}
结果:
2. 时间格式为:2021-01-04 04:16:23.609
package org.example;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
//时间格式为:2021-01-04 22:15:06.714
public class Time {
public static void test(String date) throws ParseException {
//设置时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
//将输入时间转换为ms
sdf.parse(date).getTime();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(sdf.parse(date).getTime());
System.out.println("格林威治时间:" + cal.getTime());
cal.add(Calendar.HOUR, +8);
System.out.println("北京时间:" + cal.getTime());
}
public static void main(String[] args) throws ParseException {
test("2021-01-04 04:16:23.609");
}
}
结果:
3.当前时间
package org.example;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
//时间格式为:2021-01-04 22:15:06.714
public class Time {
public static void test() throws ParseException {
Date nowTime = new Date();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(nowTime .getTime());
System.out.println("格林威治时间:" + cal.getTime());
cal.add(Calendar.HOUR, +8);
System.out.println("北京时间:" + cal.getTime());
}
public static void main(String[] args) throws ParseException {
test();
}
}
结果: