今天使用Date函数的时候,发现打印出的时间与参考答案不一致,很好奇决定打印一下Date函数的默认时间:
// 时间戳值为0是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数
// 默认为当前时间
Date date = new Date();
Date date = new Date(0);
//System.out.println(date);
System.out.println(date.toString()); // Thu Jan 01 08:00:00 CST 1970
发现它的默认时间是:08:00:00,但是记得应该是1月1日的00:00:00,这里为什么是8点呢?找了一圈发现是因为存在系统时间和本地时间,因为本地时间的时区设置为东8区,所以打印的结果是早上8点。
这里如果有特殊需要在使用Date函数时需要减去这多出来的8个小时,换算为8 * 60 * 60 * 1000 = 28800000ms
long n = sc.nextLong();
Date date = new Date(n-28800000);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss SSS");
System.out.println(sdf.format(date));
参考文章:
👍👍👍