【问题标题】:How to compare date and time in kotlin android?如何在 kotlin android 中比较日期和时间?
【发布时间】:2021-06-06 10:12:24
【问题描述】:

我在 PlayStore 上有一个应用程序,我正在构建一项功能,用户在一天内看到的广告不会超过特定数量。

我正在考虑将当前日期和时间与之前保存的日期和时间进行比较,但没有找到合适的方法。

如何比较日期和时间以了解是否已过 24 小时?

我发现但没有帮助的一些帖子:

medium.com

stackoverflow

stackoverflow

【问题讨论】:

  • 第二个链接显示了一种非常简单的方法。您甚至不需要阅读第一个代码块,因为您需要处理的只是 UTC 时间作为 Long。也许你可以描述一下你被困在哪一部分。
  • 当用户几天后打开应用程序时,我很困惑您所指的代码块是否有效。如果用户在 1 月 3 日下午 3:00 打开应用程序并在 1 月 6 日下午 3:00 重新打开它,那么当我比较它们时不会有时间过去。这就是我认为代码块会做的事情。我错了吗?
  • 嗯,当用户调用权限时,您将运行的第一段代码,您将使用 SharedPreferences 备份它。然后,当您想查看他们的权限是否仍处于活动状态时,您可以从 SharedPreferences 中恢复保存的值,并在该代码块的底部进行比较。
  • 我知道它是这样工作的,但由于它没有考虑到date 部分,它只能在同一天工作,并且在用户几天后打开应用程序时将无法工作。正确的? System.currentTimeMillis() 只会给我们当前时间而不是日期?
  • currentTimeMillis() 为您提供自纪元以来的毫秒数,因此可以用于比较自 1970 年代以来的任何时间。不限于当天。

标签: android android-studio datetime kotlin


【解决方案1】:

使用此代码检查当前日期、昨天或特定日期。将 Epoch 时间传递给此方法

// input format (we get a value as Epoch)
private val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
private val outputFormat = SimpleDateFormat("MMM dd")



// have to pass the time value as Epoch time.

private fun calculateDateMonth(time: String): String {
        var returnValue = ""
        val dateTime = DateTime((time.toLong()) * 1000L)
        val inputTime = inputFormat.parse(dateTime.toString())
        val convertDateMonth = outputFormat.format(inputTime!!)
        val timeInMilliseconds = outputFormat.parse(convertDateMonth)!!
        val mTime: Calendar = Calendar.getInstance()
        mTime.setTimeInMillis(timeInMilliseconds.time)
        val now = Calendar.getInstance()
        returnValue = when {
            now[Calendar.DATE] == mTime[Calendar.DATE] // check isToday 
            now[Calendar.DATE] - mTime[Calendar.DATE] == 1   // check Yesterday
            else -> convertDateMonth // Month and Date
        }
        return returnValue
    }

【讨论】:

  • 您正在使用糟糕的日期时间类,这些类在几年前被 JSR 310 中定义的现代 java.time 类所取代。java.time 类内置于 Android 26 及更高版本。大多数功能在早期的 Android 中都可以使用,使用带有“API 脱糖”的现代工具。
【解决方案2】:

tl;博士

[此答案使用 Java 语法。你必须翻译成 Kotlin 语法。]

if
(
    Duration                                              // Represents elapsed time on the scale of hours-minutes-seconds.
    .between(                                             // Calculates elapsed time between two points in time.    
        Instant.parse( "2021-03-23T15:30:57.013678Z" ) ,  // Last moment when an ad was show.
        Instant.now()                                     // Current moment.
    )                                                     // Returns a `Duration` object.
    .toHours()                                            // Extract total number of whole hours from the `Duration` object.
    >= 24L                                                // Test if equals-to or greater-than 24 hours.
) 
{ show ad }

java.time

你问:

…知道 24 小时是否已过?

使用 JSR 310 中定义的现代 java.time 类。java.time 类内置于 Android 26 及更高版本中。大多数功能在早期的 Android 中都可以使用最新工具的“API 脱糖”。

Instant adShown = Instant.parse( "2021-03-23T15:30:57.013678Z" ) ;
Instant now = Instant.now() ;
Duration d = Duration.between( adShown , now ) ;
long hoursSinceAdShown = d.toHours() ;
if( hoursSinceAdShown >= 24L ) { … show ad }

将您的下一个广告展示记录为标准 ISO 8601 格式的文本。

String output = Instant.now().toString() ;

2021-03-23T15:30:57.013678Z

您的问题要求两个不同的东西:

  • 每天一次
  • 每 24 小时

第一个涉及日历、日期和时区。第二个没有。我向你展示了第二个代码。


您可以使用scheduled executor service 从后台线程触发广告在特定时刻的下一次展示。搜索 Stack Overflow 以了解更多信息,因为这已被多次介绍。

【讨论】:

    猜你喜欢
    • 2016-10-10
    • 1970-01-01
    • 2021-09-20
    • 2011-01-21
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    相关资源
    最近更新 更多