1

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

Junior
  • 170
  • 2
  • 10
  • That second link shows a very easy way to do it. You don't even need to read past the first code block because all you need to deal with is the UTC time as a Long. Maybe you can describe what part of that you're stuck on. – Tenfour04 Mar 08 '21 at 14:33
  • I am confused if the code block that you are referring to will work or not when the user opens the app few days later. If the user opens the app on 3 Jan, 3:00pm and reopen it on 6 Jan, 3:00pm then no time will be passed when I compare them both. That's what I think the code block will do. Am I wrong? – Junior Mar 08 '21 at 14:46
  • Well, the first bit of code you would run when the user invokes the privilege, and you would back it up with SharedPreferences. Then when you want to see if their privilege is still active, you would restore the saved value from SharedPreferences and compare them as in the bottom part of that code block. – Tenfour04 Mar 08 '21 at 14:57
  • I understood that's how it works but since it doesn't take the `date` part into consideration it will only work in the same day and will not work when the user opens the app after few days. Right? `System.currentTimeMillis()` will only give us the current time not the date? – Junior Mar 08 '21 at 15:11
  • 1
    `currentTimeMillis()` gives you milliseconds since the epoch, so it is fine to use for comparing any time since the 1970's. It's not limited to the current day. – Tenfour04 Mar 08 '21 at 15:13
  • Ohh.. I didn't knew that. Thanks for the information:) – Junior Mar 08 '21 at 15:41

2 Answers2

3

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
1

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
    }
Tippu Fisal Sheriff
  • 2,177
  • 11
  • 19
  • You are using terrible date-time classes that were years ago supplanted by 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 modern tooling wih “API desugaring“. – Basil Bourque Mar 08 '21 at 17:43