计算日期差

时间:2019-08-28 16:22:15

标签: android kotlin calendar

我想计算用户选择的日期与当前日期之间的差值

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_home)

    var year = intent.getStringExtra("year")
    var month = intent.getStringExtra("month")
    var day = intent.getStringExtra("day")

    Log.d("select_day", "${year}.${month}.${day}")

    var selectday = Calendar.getInstance()
    selectday.set(year.toInt(), month.toInt(), day.toInt())

    var today = Calendar.getInstance()
    var yearto = today.get(Calendar.YEAR)
    var monthto = today.get(Calendar.MONTH)
    var dayto = today.get(Calendar.DAY_OF_MONTH)
    today.set(yearto, monthto+1, dayto)
    var todaym = today.timeInMillis / 86400000
    var selectdaym = selectday.timeInMillis / 86400000
    var deltil = selectdaym - todaym
    testtv.setText("${deltil.toInt()}")

}

例如,如果传递给intent的值是Year 2019 month 9 day 1 and yearto year monthto 8 day to 28,则最终结果是3而不是4。

1 个答案:

答案 0 :(得分:0)

您可以使用名为字符串的变量来存储日期,然后减去它,然后再次将其转换为日期。