工作中遇到个小bug,服务中获取的时间比当前时间少8个小时,一眼格林威治时间(GMT),在这里做个小小笔记,方便以后抄作业。
1. 直接获取系统时间
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Test9 {
public static void getGMT() {
long currentTimestamp = System.currentTimeMillis();
LocalDateTime currentDateTime = LocalDateTime.ofEpochSecond(currentTimestamp / 1000, 0, ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = currentDateTime.format(formatter);
System.out.println("系统时间为:"+formattedDateTime);
}
public static void main(String[] args) {
getGMT();
}
}
执行方法,得到结果为
可以看到确实早了8个小时
2. 获取东八时区时间
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Test9 {
public static void getTimeStamp() {
long currentTimestamp = System.currentTimeMillis();
LocalDateTime currentDateTime = LocalDateTime.ofEpochSecond(currentTimestamp / 1000, 0, ZoneOffset.UTC);
LocalDateTime newDateTime = currentDateTime.plus(8, ChronoUnit.HOURS);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = newDateTime.format(formatter);
System.out.println("当前时区时间为:"+formattedDateTime);
}
public static void main(String[] args) {
getTimeStamp();
}
}
再次执行
可以看到这次是正确的
3. 使用Date类获取系统当前时间
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
public class Test9 {
public static void getDate() {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Date时间为:"+dateFormat.format(date));
}
public static void main(String[] args) {
getDate();
}
}
执行方法,得到正确结果