I'd like to program an app that, will be avaliable for only a month. I'd like to check when starting the app whether it's over that that given date( 2020 may. 22, but I don't know how to do that. Could somebody tell me how to compare the current time with a preseted date?
-
Have look into date comparision https://stackoverflow.com/questions/2592501/how-to-compare-dates-in-java OR https://www.geeksforgeeks.org/compare-dates-in-java/ – ajayg2808 Apr 22 '20 at 17:18
-
Does this answer your question? [How to compare dates in Java?](https://stackoverflow.com/questions/2592501/how-to-compare-dates-in-java) – Ryan M Apr 22 '20 at 23:38
3 Answers
put this code in your app's onCreate()
method and change the date. The doSomething()
method will be called once the date expires.
String expiryDateString = "22-May-2020"; // upcoming date
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date expiryDate = formatter.parse(expiryDateString);
if(System.currentTimeMillis() > expiryDate.getTime()){
// app is expired
doSomething();
}
but please note that this is not a secure method as one can change the system time and date and this test fails. So a better method would be to use flags in the server and check it every time the app starts.
-
Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Apr 23 '20 at 04:58
Make a static variable that contains the current time and check it when the program starts (or in a loop if that's what you require)
public class Main {
private static final long DATE_STARTED = 1587575414548;
if(DATE_STARTED + 2592000000 < System.currentTimeInMillis()) { // 2592000000 is 30 days in milliseconds
// Handle stuff here
}
}

- 68
- 1
- 5
Going off of @JackChap77's comment, if you want to find the current time, use
new Date().getTime()
to retrieve the current time in milliseconds and then store that in a final variable. Make sure to only use it once, though, as you don't want to retrieve the current time each time the program is loaded.

- 76
- 2