简体   繁体   中英

How to compare date and time in kotlin android?

I have an app on the PlayStore and I am building a feature where the user will not see ads more than a specific number in one day.

I am thinking about comparing the current date and time to the previously saved one but haven't find a proper way to do that.

How can I compare date and time to know if 24 hours have passed or not?

Some posts that I found but not helpful:

medium.com

stackoverflow

stackoverflow

tl;dr

[This Answer uses Java syntax. You'll have to translate to Kotlin syntax.]

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

You asked:

… know if 24 hours have passed or not?

Use the modern java.time classes defined in JSR 310. The java.time classes are built into Android 26 and later. Most of the functionality is available in earlier Android using the latest tooling's “API desugaring“.

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 }

Record your next ad-showing as text in standard ISO 8601 format.

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

2021-03-23T15:30:57.013678Z

Your Question asked for two different things:

  • Once per day
  • Every 24 hours

The first involves a calendar, dates, and a time zone. The second does not. I showed you code for the second.


You can use a scheduled executor service to trigger from a background thread the next showing of an ad at a specific moment. Search Stack Overflow to learn more as this has been covered many times already.

Use this code to check the current date, Yesterday or Particulardate. Pass Epoch time to this method

// 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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM