java 计算当前时间和未来时间之间的时差
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12679343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate time difference between current and future time
提问by Prachur
I want to calculate time difference in milliseconds from current time of a day(11 am , 1 october,2012) and time at midnight for the same day (11 pm 59 m 59s , 1 october , 2012.
我想计算一天的当前时间(2012 年 10 月 11 日上午 11 点)和同一天午夜时间(2012 年 10 月 1 日上午 11 点 59 分 59 秒)的时差(以毫秒为单位)。
I have tried this
我试过这个
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 59);
cal.add(Calendar.HOUR, 23);
cal.add(Calendar.MINUTE, 59);
cal.getTime().getTime() - today.getTime();
here today is the current date.
今天是当前日期。
But when i print long values of cal and today , the time difference if of 86400 approx one day.
但是当我打印 cal 和 today 的长值时,时差为 86400 大约一天。
回答by iTurki
Use cal.set()
instead of cal.add()
使用cal.set()
代替cal.add()
Calendar cal = Calendar.getInstance();
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.HOUR, 23);
cal.set(Calendar.MINUTE, 59);
long diff = cal.getTime().getTime() - today.getTime();
回答by Rohit Jain
You can set your date to newly created Calendar instance..
And then compare it with current instance using getTimeInMillis()
您可以将日期设置为新创建的 Calendar 实例。然后使用它与当前实例进行比较 getTimeInMillis()
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.DATE, 1);
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.YEAR, 2012);
long difference = cal.getTimeInMillis() - Calendar.getInstance().getTimeInMillis();