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.
Use the Calendar class:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -5);
long fiveDaysAgo = cal.getTimeInMillis();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With