System.currentTimeMillis() 獲取的是返回當前的計算機時間,時間的表達格式為當前計算機時間和GMT時間(格林威治時間)1970年1月1號0時0分0秒所差的毫秒數。
當前計算機時間是跟你的計算機所在時區是有關的!!!
故當前計算機時間和System.currentTimeMillis()所在時區可能不一樣,會相差一些小時【中國東八區相差8小時】,這點使用時要注意。最好使用 java.util.Calendar 可以設置時區。
public static void main(String[] args) { int currentDay=TimeDateUtil.getCurrentDay(); long currentTime = currentDay*TimeDateUtil.ONEDAY; long tomorrowZeroTime =currentTime + TimeDateUtil.ONEDAY*2; int todayZeroTimeReturnInt = TimeDateUtil.getTodayZeroTimeReturnInt(); //todayZeroTimeReturnInt:1605024000,currentDay:18576,currentTime:1604966400000 System.out.println("todayZeroTimeReturnInt:"+todayZeroTimeReturnInt+",currentDay:"+currentDay+",currentTime:"+currentTime+",currentSystemTime:"+System.currentTimeMillis()); System.out.println("nowZeroTime:"+String.format("%tc", todayZeroTimeReturnInt*1000L));//當前時間的凌晨時間 System.out.println("systemCurrentTime:"+String.format("%tc", System.currentTimeMillis())); System.out.println("currentTime:"+String.format("%tc", currentTime)); System.out.println("tomorrowZeroTime:"+String.format("%tc", tomorrowZeroTime));
} /** * 時間日期工具類 * @author 哈皮 * */ public class TimeDateUtil { /** * 一天的時間 */ public static final long ONEDAY = 3600*24*1000; /**當前總天*/ public static int getCurrentDay(){ return getTodayZeroTimeReturnInt()/ONE_DAY; } /** * 獲取今天零時的時間 * @return 零時以int類型返回的數值 */ public static int getTodayZeroTimeReturnInt(){ long todayZeroTime = getTodayZeroTime(); return (int) (todayZeroTime/1000); } /** * 獲取今天零時的時間 * @return 零時以long類型返回的數值 */ public static long getTodayZeroTime(){ long now = System.currentTimeMillis(); long more = now%ONEHOUR; int nowHour = getHour(); long zeroTime = now-(nowHour*ONEHOUR+more); return zeroTime; } }
控制台輸出:
todayZeroTimeReturnInt:1605110400,currentDay:18577,currentTime:1605052800000,currentSystemTime:1605147353125
nowZeroTime:周四 11月 12 00:00:00 CST 2020
systemCurrentTime:周四 11月 12 10:15:53 CST 2020
currentTime:周三 11月 11 08:00:00 CST 2020
tomorrowZeroTime:周五 11月 13 08:00:00 CST 2020
結果會發現 System.currentTimeMillis()除以每天的毫秒數變成天數currentDay。
這里已經這里已經不准確了,currentDay=1605110400/86400000=18576.6666 其實是除不盡的,會有余數,而余數被舍去了。所以,最后currentDay 再乘以 每天毫秒數,轉化為當前時間變成了和零點相差8小時。