【问题标题】:How to calculate the total number of days passed [duplicate]如何计算过去的总天数[重复]
【发布时间】:2012-09-10 18:11:08
【问题描述】:

可能重复:
Calculate date/time difference in java

我正在为用户提供使用日期选择器选择日期的选项。是否有任何内置方法可以用来计算用户选择日期和今天日期的持续时间(以天为单位)。

【问题讨论】:

  • 不,没有内置方法。您必须编写这 4 行代码。令人沮丧:(
  • 嘿伙计,你有任何之前实现过的代码吗?

标签: android


【解决方案1】:
Date today = new Date(); // the date of today
Date target = new Date(); // the date of when the user picks

long todayEpoch = today.getTime(); // or can use = System.currentTimeMillis();
long targetEpoch = target.getTime();

long daysInMs = targetEpoch - todayEpoch; //days in MS's

//the # of days
float days = (daysInMs/1000/60/60/12);

【讨论】:

  • 然后直接进入 Epoch,以以太方式 Date 类可以正常工作。
  • 这不考虑双周岁(366 天)
【解决方案2】:

以毫秒为单位获取两次之间的差异。你可以通过 Java 的 Calendar 类获取 Days。

【讨论】:

    【解决方案3】:

    我不喜欢回答这个问题,因为有 数百万 个这样的问题(在发布问题之前使用搜索选项)。使用Joda Time。有一个Period 类,对你很有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-10
      • 2011-10-11
      • 1970-01-01
      • 2017-04-02
      相关资源
      最近更新 更多