subtracting two days from current date in epoch milliseconds java [duplicate]

旧时模样 提交于 2019-12-01 21:37:04

问题


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.

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?


回答1:


try

    long millis = System.currentTimeMillis() - 2 * 24 * 60 * 60 * 1000; 
    Date date = new Date(millis);

it definitely works




回答2:


Use Calendar API like this to subtract 2 days from a Date object:

Calendar c = Calendar.getInstance();
c.setTime(d);
c.add(Calendar.DATE, -2);
d.setTime( c.getTime().getTime() );

long millisec = d.getTime();



回答3:


Your code is alright , your variable d should be at offset of 48 hours from the current time on your server.

Make sure the server and your clients are running on the same time otherwise 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.




回答4:


try this

   long diff = Math.abs(d1.getTime() - d2.getTime());
   long diffDays = diff / (2*24 * 60 * 60 * 1000);



回答5:


Avoid the old java.util.Date and .Calendar classes as they are notoriously troublesome.

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 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.

Quick example in Joda-Time 2.7 ( as this is really a duplicate Question, see others for more info ).

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone );
DateTime fortyEightHoursAgo = now.minusHours( 48 );
DateTime twoDaysAgo = now.minusDays( 2 );


来源:https://stackoverflow.com/questions/15607500/subtracting-two-days-from-current-date-in-epoch-milliseconds-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!