【发布时间】:2013-06-17 09:00:57
【问题描述】:
我正在使用 unix 时间戳将购买日期存储在我的应用程序中。 样本数据:1371463066
我想根据天数和当天时间戳的差异进行一些操作。 例如:如果购买日期和当前日期之间的天数是 5 天,则再次发送电子邮件反馈。
如何使用 java 获取两个时间戳之间的天数差?
【问题讨论】:
-
你有没有尝试过?
我正在使用 unix 时间戳将购买日期存储在我的应用程序中。 样本数据:1371463066
我想根据天数和当天时间戳的差异进行一些操作。 例如:如果购买日期和当前日期之间的天数是 5 天,则再次发送电子邮件反馈。
如何使用 java 获取两个时间戳之间的天数差?
【问题讨论】:
我还没有测试过,但你可以尝试做这样的事情:
Date purchasedDate = new Date ();
//multiply the timestampt with 1000 as java expects the time in milliseconds
purchasedDate.setTime((long)purchasedtime*1000);
Date currentDate = new Date ();
currentDate .setTime((long)currentTime*1000);
//To calculate the days difference between two dates
int diffInDays = (int)( (currentDate.getTime() - purchasedDate.getTime())
/ (1000 * 60 * 60 * 24) )
【讨论】:
Unix 时间戳是自 1.1.1970 以来的秒数。如果你有 2 个 unix 时间戳,那么全天的差异是
int diff = (ts1 - ts2) / 3600 / 24
【讨论】:
您可以尝试使用日历(这也将允许您使用时区):
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(1371427200l * 1000l);
Calendar newCalendar = Calendar.getInstance();
newCalendar.setTimeInMillis(1371527200l * 1000l);
// prints the difference in days between newCalendar and calendar
System.out.println(newCalendar.get(Calendar.DAY_OF_YEAR) - calendar.get(Calendar.DAY_OF_YEAR));
输出:
1
【讨论】: