2

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.

Poppy
  • 2,902
  • 14
  • 51
  • 75

7 Answers7

10

Use the Calendar class:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -5);
long fiveDaysAgo = cal.getTimeInMillis();
cmbaxter
  • 35,283
  • 4
  • 86
  • 95
  • Is it possible to calculate 5 day before and after at the same time with single instance of Calendar? – Amir Jun 07 '16 at 16:43
3

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
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
1
Date d = initDate();//intialize your date to any date 
Date dateBefore = new Date(d.getTime() - n * 24 * 3600 * 1000 ); //Subtract n days

Also possible duplicate .

Community
  • 1
  • 1
voidMainReturn
  • 3,339
  • 6
  • 38
  • 66
1

That currentTimestamp must be passed to a Calendar instance. from Calendar you can subtract X days. Get the milliseconds from calendar and is done.

1

You can play aorund with the following code snippet, to form it the way you want:

Calendar c = Calendar.getInstance();
c.setTimeInMillis(milliSeconds);
c.add(Calendar.DATE, -5);

Date date = c.getTime();
Peter Jaloveczki
  • 2,039
  • 1
  • 19
  • 35
1
  Calendar calendar=Calendar.getInstance();
  calendar.add(Calendar.DATE, -5);

using Java.util.Calendar Class

Calendar.DATE

This is the field number for get and set indicating the day of the month. , to subtract 5 days from the current time of the calendar, you can achieve it by calling.

bNd
  • 7,512
  • 7
  • 39
  • 72
0

Try this..

long timeInMillis = System.currentTimeMillis();

Calendar cal = Calendar.getInstance();

cal.setTimeInMillis(timeInMillis);

cal.set(Calendar.DATE, cal.get(Calendar.DATE)-5);

java.util.Date date1 = cal.getTime();

System.out.println(date1);
Anand Devaraj
  • 725
  • 4
  • 12
  • 22