简体   繁体   中英

How to deduct current time by 2 seconds

How to deduct the current time by 2 seconds?

I'd try this code but it does'nt work for me.

Date interestingDate = new Date();
(new Date()).getTime() - interestingDate.getTime();

I don't know to how to code this.

datenow=now.getTime().toLocaleString();
newdate = datenow - 2

I would like to get the result like this:

9 Mar 2014 2_15_17 - 2 = 9 Mar 2014 2_15_15

that is the result by deducting 2 seconds... How?

this is my code:

Calendar now = Calendar.getInstance(); datenow=now.getTime().toLocaleString();

i'd try

datenow = new Date(now.getTime() - TimeUnit.SECONDS.toMillis(2));

but i've got an error on " new Date(now.getTime() - TimeUnit.SECONDS.toMillis(2)); "

still got an error

Calendar now = Calendar.getInstance(); System.out.println(now.getTime() + " " + now.get(Calendar.SECOND));

now.add(Calendar.SECOND, -2); System.out.println(now.getTime() + " " + now.get(Calendar.SECOND));

datenow=now.add(Calendar.SECOND, -2);

I have another solution from the suggested answer below.

How about getting the last two digits?

example:

9 Mar 2014 16_23_45.jpeg <-- now get the 45.jpeg

45.jpeg <--- remove the .jpeg so that the 45 will be retain and convert it to value

now 45 - 2 = 43

now get the 9 Mar 2014 16_23_45.jpeg but remove the 45.jpeg and replace it to 43.jpeg.

Maybe that is the best way but i dont know how to cade that in java.

Assuming you meant subtract:

Date now = new Date();
Date nowLess2Sec = new Date(now.getTime() - TimeUnit.SECONDS.toMillis(2));

You can try this also..

Calendar c1 = Calendar.getInstance();
System.out.println(c1.getTime() + " " + c1.get(Calendar.SECOND));

c1.add(Calendar.SECOND, -2);
System.out.println(c1.getTime() + " " + c1.get(Calendar.SECOND));

使用Joda-Time库可以更轻松地完成这项工作。

java.util.Date date = DateTime.now().minusSeconds(2).toDate();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM