【问题标题】:How to calculate the exact days in Age Calculator between the date entered & the current date?如何在年龄计算器中计算输入日期和当前日期之间的确切天数?
【发布时间】:2022-01-25 02:15:23
【问题描述】:
val theDate=sdf.parse(selectedDate)

            theDate?.let {

                val selectedDateInMin=theDate.time / 60000
                val selectedDateInYear=(theDate.time/ 31536000000)
                val selectedDateInMonth=(theDate.time)/2629746000
                val selectedDateInDay=(theDate.time)/86400000

                val currentDate=sdf.parse(sdf.format(System.currentTimeMillis()))
                currentDate?.let {

                    val currentDateInMin=currentDate.time/60000
                    val currentDateInYear=(currentDate.time/ 31536000000)
                    val currentDateInMonth=(currentDate.time)/2629746000
                    val currentDateInDay=(currentDate.time)/86400000

                    val differenceInMin = currentDateInMin-selectedDateInMin
                    val differenceInYear=currentDateInYear-selectedDateInYear-1

                    val leap_days=(differenceInYear*(0.24)).toInt()

                    val differenceInMonth=currentDateInMonth-selectedDateInMonth-(differenceInYear*12)

                    val differenceInDay=currentDateInDay-selectedDateInDay-(differenceInYear*365)-(differenceInMonth*31)-leap_days

当我计算 Days 差异时,我必须减去包含在 month 差异中的天数。那么我将如何计算该月是否有 28 天或 31 天或 30 天,什么没有。我必须乘以 differenceInMonth 吗?我将如何概括获取特定月份中确切天数的公式,例如2个月或4个月有多少天?

【问题讨论】:

标签: java android kotlin math calculation


【解决方案1】:
import java.text.SimpleDateFormat
import java.time.Duration

val sdf = SimpleDateFormat("yyyy-MM-dd hh:mm:ss")

val theDate= sdf.parse("2022-03-14 17:09:18")
val now = sdf.parse(sdf.format(System.currentTimeMillis()))

val duration = Duration.between(now.toInstant(), theDate.toInstant()).toDays()

println("$duration days")

【讨论】:

  • 这不起作用..!!
  • 你能指定什么吗?它不编译吗?它会给出错误的结果吗?只喊没用……
  • 实际上它返回了错误的结果。 val currentDate=sdf.parse(sdf.format(System.currentTimeMillis())) currentDate?.let { val differenceInDay=Duration.between(currentDate.toInstant(), theDate.toInstant()).toDays() day_tv?.text =differenceInDay.toString() } } },year,month,day) 例如,当我选择日期 2003 年 3 月 7 日时,它返回 18 年 10 个月 -6889 天,而我的代码返回 18 年 10 个月 14 天.
  • 您的代码似乎不正确。从 2003 年 3 月 7 日(包括)到 2022 年 1 月 25 日(但不包括)这段时间的值是 6899 天,即 18 年 10 个月 18 天。
猜你喜欢
  • 2014-05-30
  • 2023-02-22
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-13
  • 1970-01-01
  • 2012-12-13
相关资源
最近更新 更多