java的 System.currentTimeMillis() 与时区
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小时。
源码,是痛苦的,又是快乐的,如果没有这痛苦,也就没有了这快乐!
本文作者:好Wu赖
本文链接:https://www.cnblogs.com/erlongxizhu-03/p/13962545.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!