【问题标题】:How to find number of days between two unix timestamps in java如何在java中查找两个unix时间戳之间的天数
【发布时间】:2013-06-17 09:00:57
【问题描述】:

我正在使用 unix 时间戳将购买日期存储在我的应用程序中。 样本数据:1371463066

我想根据天数和当天时间戳的差异进行一些操作。 例如:如果购买日期和当前日期之间的天数是 5 天,则再次发送电子邮件反馈。

如何使用 java 获取两个时间戳之间的天数差?

【问题讨论】:

  • 你有没有尝试过?

标签: java timestamp


【解决方案1】:

我还没有测试过,但你可以尝试做这样的事情:

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) )

【讨论】:

  • (currenttime - purchacedtime)/24*60*60 不起作用吗?
【解决方案2】:

Unix 时间戳是自 1.1.1970 以来的秒数。如果你有 2 个 unix 时间戳,那么全天的差异是

int diff = (ts1 - ts2) / 3600 / 24

【讨论】:

  • 我认为这不会考虑闰年
【解决方案3】:

您可以尝试使用日历(这也将允许您使用时区):

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

【讨论】:

  • 如果第二个日期不同年份怎么办?
  • 啊,是的,我愚蠢地以为会是同一年,不知道为什么。在这种情况下,您需要比较时间戳,而不是比较 DAY_OF_YEAR 值,就像 Juned Ashad 在他/她的回答中所做的那样。不过,您仍然可以从日历中执行此操作。
猜你喜欢
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多