java - 几行代码判断当前时间是否是今天的下午,好像和预想的不一样
PHP中文网
PHP中文网 2017-04-17 17:22:34
[Java讨论组]

图片描述

输出一直是false,比较郁闷,我就在刚才下午测试的

PHP中文网
PHP中文网

认证0级讲师

全部回复(4)
大家讲道理

取模运算的优先级等于乘法运算,从左到右结合。

你的代码等价于long today = curTime - (curTime % 24) * 60 * 60 * 1000;

改一下括号就好了:long today = curTime - curTime % (24 * 60 * 60 * 1000);

黄舟

首先是括号的问题,下面这行要加括号,不加的话运算符优先级会导致数据错误。

long todayMillis = currentMillis - currentMillis % (24 * 60 * 60 * 1000L);

你的运算逻辑

long todayMillis = currentMillis - currentMillis % (24 * 60 * 60 * 1000L);
currentMillis - todayMillis

可以化简为:

currentMillis - (currentMillis - currentMillis % (24 * 60 * 60 * 1000L)) = currentMillis % (24 * 60 * 60 * 1000L) 

最后代码相当于:

currentMillis % (24 * 60 * 60 * 1000L) > 12 * 60 * 60 * 1000L

其次这种实现方式忽略了一点:

时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。

也就是说这么算出来的结果应该去比较 currentMillis % (24 * 60 * 60 * 1000L) > 4 * 60 * 60 * 1000L

最后这种实现方式太繁琐,不如直接用
Calendar.getInstance().get(Calendar.HOUR_OF_DAY) >= 12 方便

PHP中文网
int i = Calendar.getInstance(Locale.US).get(Calendar.AM_PM);
System.out.println((i == Calendar.PM ? "pm" : "am"));
PHP中文网

时间格式有问题。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号