java 以纪元毫秒为单位从当前日期中减去两天java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15607500/
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
subtracting two days from current date in epoch milliseconds java
提问by p0tta
I am trying to do something really simple. I am trying to subtract 2 days from the current day. I get the number of hours from the UI. So in this example, I get 48 hours from the UI. I am doing the following and I don't know what i'm doing wrong here. I think the result of this is it only subtracts a few minutes from the time.
我正在尝试做一些非常简单的事情。我试图从当天减去 2 天。我从用户界面获得小时数。所以在这个例子中,我从 UI 获得了 48 小时。我正在做以下事情,我不知道我在这里做错了什么。我认为这样做的结果是它只从时间中减去了几分钟。
long timeInEpoch = (currentMillis()/1000 - (48 * 60 * 60)); //48 comes from UI
public long currentMillis(){
return new Date().getTime();
}
d = new Date(timeInEpoch * 1000);
I also tried
我也试过
d1 = new Date(timeInEpoch);
Nothing seems to work. What am I doing wrong here?
似乎没有任何效果。我在这里做错了什么?
回答by Evgeniy Dorofeev
try
尝试
long millis = System.currentTimeMillis() - 2 * 24 * 60 * 60 * 1000;
Date date = new Date(millis);
it definitely works
它绝对有效
回答by anubhava
回答by Avinash Singh
Your code is alright , your variable d should be at offset of 48 hours from the current time on your server.
您的代码没问题,您的变量 d 应该与服务器上的当前时间相距 48 小时。
Make sure the server and your clients are running on the same timeotherwise request your server admins to fix the time on your deployment machine.
确保服务器和您的客户端同时运行,否则请您的服务器管理员修复部署机器上的时间。
You would also notice this difference if your client is opening a browser in e.g. Japan and your server is running in USA because of the standard time difference.
如果您的客户端在例如日本打开浏览器而您的服务器在美国运行,您也会注意到这种差异,因为标准时差。
回答by PSR
try this
试试这个
long diff = Math.abs(d1.getTime() - d2.getTime());
long diffDays = diff / (2*24 * 60 * 60 * 1000);
回答by Basil Bourque
Avoid the old java.util.Date and .Calendar classes as they are notoriously troublesome.
避免使用旧的 java.util.Date 和 .Calendar 类,因为它们是出了名的麻烦。
Use either Joda-Time or the new Java.time package built into Java 8. Search StackOverflow for hundreds of Questions and Answers on this.
使用 Joda-Time 或 Java 8 中内置的新 Java.time 包。在 StackOverflow 上搜索数百个问题和答案。
Joda-Time offers methods for adding and subtracting hour, days, and more. The math is done in a smart way, handling Daylight Saving Time nonsense and other issues.
Joda-Time 提供了加减小时、天等的方法。数学以一种聪明的方式完成,处理夏令时的废话和其他问题。
Quick example in Joda-Time 2.7 ( as this is really a duplicate Question, see others for more info ).
Joda-Time 2.7 中的快速示例(因为这确实是一个重复的问题,请参阅其他人了解更多信息)。
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone );
DateTime fortyEightHoursAgo = now.minusHours( 48 );
DateTime twoDaysAgo = now.minusDays( 2 );