2

在我的购物车应用程序中,我将所有购买日期存储在时间戳中。

假设,我想获取购买日期前 n 天的时间戳(n 是可配置的)。我将如何使用 java 获得它?

例如:像 purchaseateBefore5days = currentTimestamp_in_days - 5 这样的东西;我正在使用当前时间戳

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

我怎样才能从中减去 n 天。我是初学者。请帮助解决这个问题。

4

7 回答 7

10

使用Calendar类:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -5);
long fiveDaysAgo = cal.getTimeInMillis();
于 2013-06-18T11:33:27.083 回答
3

您可以使用 Java 中的Calendar类,使用它的set()方法从Calendar.DATE字段中添加/减去所需的天数。

n要从今天减去天数,请使用c.get(Calendar.DATE)-n。示例代码:

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
于 2013-06-18T11:32:18.813 回答
1
Date d = initDate();//intialize your date to any date 
Date dateBefore = new Date(d.getTime() - n * 24 * 3600 * 1000 ); //Subtract n days

可能重复。

于 2013-06-18T11:30:16.877 回答
1

currentTimestamp 必须传递给 Calendar 实例。您可以从日历中减去 X 天。从日历中获取毫秒数并完成。

于 2013-06-18T11:31:31.160 回答
1

您可以使用以下代码片段播放 aorund,以按照您想要的方式形成它:

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

Date date = c.getTime();
于 2013-06-18T11:31:43.170 回答
1
  Calendar calendar=Calendar.getInstance();
  calendar.add(Calendar.DATE, -5);

使用Java.util.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.

于 2013-06-18T11:32:31.597 回答
0

尝试这个..

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);
于 2013-06-18T12:02:58.730 回答