【问题标题】:Difference between two dates not working properly?两个日期之间的差异无法正常工作?
【发布时间】:2020-03-06 20:17:24
【问题描述】:

我正在尝试查找选中的date 与今天的date 差异是否等于或大于18 年。

为了获取今天的日期,下面是我的代码

private val simpleDateFormat = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault())
    private val date = Date()
    private val todayDate = simpleDateFormat.parse(simpleDateFormat.format(date)).time
private val cal = Calendar.getInstance()

 cal.time = date
 val date = simpleDateFormat.parse("12-11-2001").time
val years = (todayDate - date) / (1000L * 60 * 60 * 24 * cal.getActualMaximum(Calendar.DAY_OF_YEAR))

现在我选择的日期是 2001 年 12 月 11 日,今天的日期是 2019 年 11 月 11 日,所以它应该显示 17 年,但显示的是 18 年。即使我选择 13,14 或 2001 年 11 月 15 日,它也会显示 18 年而不是 17 年,但如果我选择 2001 年 11 月 16 日,那么它会显示 17 年。我无法理解为什么会发生这种行为。

【问题讨论】:

  • private val todayDate = simpleDateFormat.parse(simpleDateFormat.format(date)) 多么奇怪的一行。它实际上什么也没做。使用date 而不是全部。
  • @VladyslavMatviienko 感谢您优化我的代码,但仍然面临同样的问题
  • 我认为您需要使用DatePickerDialog,它将根据您的要求轻松实现。
  • 当用户选择日期时,我正在使用 DatePickerDialog。只是为了方便我的问题,我已经硬编码了选定的日期@ParthLotia
  • 您需要用户是否年满 18 岁这样的条件?

标签: android datetime kotlin android-date


【解决方案1】:

最好将java.time API 用于此类任务:

import java.time.*
import java.time.format.*
import java.time.temporal.ChronoUnit

fun main() {
    val today = LocalDate.now()
    val date = LocalDate.parse("12-11-2001", DateTimeFormatter.ofPattern("dd-MM-yyyy"))

    val diff = ChronoUnit.YEARS.between(date, today)

    println("Diff between $date and $today is $diff years")
}

如果由于 minSdkVersion 限制还不能使用java.time,可以使用ThreeTen Backport 项目及其Android 适配ThreeTenABP

【讨论】:

    【解决方案2】:
    • 试试这个可能对你有帮助。

      context  = YourActivity.this;
      btn_datePicker = findViewById(R.id.btn_datePicker);
      
      Calendar calendar = Calendar.getInstance();
      final int day = calendar.get(Calendar.DAY_OF_MONTH);
      final int month = calendar.get(Calendar.MONTH);
      final int year = calendar.get(Calendar.YEAR);
      
      btn_datePicker.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              datePicker = new DatePickerDialog(context, new   DatePickerDialog.OnDateSetListener() {
                  @Override
                  public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
      
                      if (i > year - 18 && i1 + 1 > month - (12 * 18)) {
      
      
                          Toast.makeText(context, "Select Proper birth date", Toast.LENGTH_SHORT).show();
      
                      } else {
                          Toast.makeText(context, ""+i2 + "/" + (i1 + 1) + "/" + i, Toast.LENGTH_SHORT).show();
                      }
      
      
                  }
              }, year, month, day);
              datePicker.show();
          }
      });
      

    【讨论】:

    • 根据yourtextview.setText中的要求格式化日期
    • 不起作用。我认为设置日期没有问题。问题在于今天和选定日期之间的差异
    • 我不知道它对我有用,我也编辑我的答案,请检查。
    【解决方案3】:
    public int GetDifference(long start,long end){
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(start);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int min = cal.get(Calendar.MINUTE);
        long t=(23-hour)*3600000+(59-min)*60000;
    
        t=start+t;
    
        int diff=0;
        if(end>t){
            diff=(int)((end-t)/ TimeUnit.DAYS.toMillis(1))+1;
        }
    
        int leapYear = (diff/365)/4;
    
    
        return  (diff-leapYear)/365;
    }    
    

    你需要定义闰年,这段代码返回 17

    【讨论】:

      【解决方案4】:

      这是获取两个日期之间的年数(两个日期之间的差异)的正确解决方案。

      在 onCreate 方法中添加此代码。

      var d1: Date? = null
      var d2: Date? = null
      val dateStart = "12-11-2001"
      val dateStop = "11-11-2019"
      val format = SimpleDateFormat("dd-MM-yyyy")
      d1 = format.parse(dateStart)
      d2 = format.parse(dateStop)
      Log.d("Year_Difference", getDiffYears(d1, d2).toString())
      

      在您的活动中添加这两种方法。

      fun getDiffYears(first: Date, last: Date): Int {
              val a = getCalendar(first)
              val b = getCalendar(last)
              var diff = b.get(YEAR) - a.get(YEAR)
              if (a.get(MONTH) > b.get(MONTH) || a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE)) {
                  diff--
              }
              return diff
          }
      
      
      fun getCalendar(date: Date): Calendar {
              val cal = Calendar.getInstance(Locale.US)
              cal.time = date
              return cal
          }
      

      【讨论】:

      • 我认为您没有正确导入 MONTH,就我而言它工作正常。
      猜你喜欢
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      • 1970-01-01
      • 2018-10-02
      • 1970-01-01
      • 2014-02-12
      相关资源
      最近更新 更多