Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the timestamp of previous dates in java? [duplicate]

Tags:

java

timestamp

In my shopping cart application, I am storing all the purchase dates in timestamp.

Suppose, I want to get the timestamp of purchase date n days before (n is configurable). How will I get it using java?

example: something like purchasedateBefore5days = currentTimestamp_in_days - 5; I am getting current timestamp using

long currentTimestamp = Math.round(System.currentTimeMillis() / 1000);

How can i subtract n days from it. I am a beginner. Please help on this.

like image 694
Poppy Avatar asked Jan 20 '26 18:01

Poppy


2 Answers

Use the Calendar class:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -5);
long fiveDaysAgo = cal.getTimeInMillis();
like image 173
cmbaxter Avatar answered Jan 23 '26 06:01

cmbaxter


You can use the Calendar class in Java , use its set() method to add/subtract the required number of days from the Calendar.DATE field.

To subtract n days from today , Use c.get(Calendar.DATE)-n. Sample code :

Calendar c = Calendar.getInstance();
System.out.println(c.getTime()); // Tue Jun 18 17:07:45 IST 2013
c.set(Calendar.DATE, c.get(Calendar.DATE)-5);
System.out.println(c.getTime()); // Thu Jun 13 17:07:45 IST 2013
like image 33
AllTooSir Avatar answered Jan 23 '26 07:01

AllTooSir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!