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

≡放荡痞女 提交于 2019-12-01 19:41:47

try

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

it definitely works

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();

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.

try this

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

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