如何计算24小时过去与否 [英] How to count that 24 Hours passed or not

查看:79
本文介绍了如何计算24小时过去与否的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个问题,就是在按钮单击事件之后,以共享的首选项来节省当前设备的时间.例如:该日期(2015年7月27日)上午11:05.之后,当用户进行相同的活动时,我必须根据项目要求在接下来的24小时内更改布局文件,直到(2015年8月28日上午11:05)为止.但是我面临的问题是,在这种情况下,从单击按钮的时间(凌晨11:05)起是否经过了24小时,我该如何获取该信息.任何帮助将不胜感激.谢谢.

I am facing a problem that I am saving the current device time in shared preferences behind a button click event. E.g: 11:05 am for the date(27-08-2015). After that when the user come to the same activity I have to change the layout file for the next 24 hours till (11:05 am for the date 28-08-2015) as per the project requirements. But I am facing the problem that how can I get that if 24 hours has been passed or not from the time of button click which was 11:05 am in this case. Any sort of help will be highly appreciated. Thank You.

推荐答案

如果要"24小时后",请使用纯UTC时间.最简单的方法是使用原始的毫.

If you want "24 hours later", use pure UTC time. Simplest is to use the raw millis.

// Save current time
long savedMillis = System.currentTimeMillis();

// Check time elapsed
if (System.currentTimeMillis() >= savedMillis + 24 * 60 * 60 * 1000) {
    // time has elapsed
}

如果您想在明天的同一天之后",则必须记住时区,或者只是将其转换为未分区的文本.

If you want "after same time of day tomorrow", you have to either remember the timezone, or simply convert to un-zoned text.

SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

// Save current time
String savedTime = df.format(new Date()); // Applies local time zone 1

// Check time elapsed
Calendar cal = Calendar.getInstance();
cal.setTime(df.parse(savedTime)); // Applies local time zone 2
cal.add(Calendar.DAY_OF_MONTH, 1); // Adjusts for DST in local time zone 2
if (System.currentTimeMillis() >= cal.getTimeInMillis()) {
    // time has elapsed
}

说明

new Date()返回一个以UTC时间表示的时刻.
df.format 返回当前默认时区中该瞬间的文本表示,即在调用时(或在SimpleDateFormat时)对JVM生效的时区.已创建).

new Date() returns an instant in UTC time.
df.format returns text representation of that instant in the current default timezone, i.e. the timezone in effect for the JVM at the time the call is made (or rather when the SimpleDateFormat was created).

稍后, df.parse 会再次使用当前默认时区将文本解析为UTC时间的瞬间,但该时区可能与在调用 df.format 时使用.
cal.setTime Calendar 更新为UTC时间中的时刻.
cal.add Calendar 更新为1天后的同一时间,并根据需要调整当前默认时区中的DST.
cal.getTimeInMillis()是当地时间段中保存时间1天后一天中同一时间的UTC毫秒.

Later on, df.parse will parse that text back into an instant in UTC time, again using the current default timezone, but that may be a different timezone than used when df.format was called.
cal.setTime updates the Calendar to the instant in UTC time.
cal.add updates the Calendar to the same time 1 day later, adjusting for DST in the current default timezone, if needed.
cal.getTimeInMillis() is the UTC millis of the same time of day, 1 day after the saved time, in local time zone.

这篇关于如何计算24小时过去与否的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆