Reputation: 153
For something I am creating, users are allowed to purchase an item that will last X amount of days. The expiry date of the item is stored in my MySQL database and I decided to store it as an integer, which represents the amount of days that have gone by within this year. I then use this value to check if the current amount of days gone by is bigger than the expiry, and then expire the item.
However, what if the item was purchased in december, on the 360th day, and the expiry date was 30 days later, on the ~25th day of the next year, and I compared the two values - the item would expire early as 360 > 25.
while (set.next()) {
String uuid = set.getString("UUID");
String rank = set.getString("Rank");
int expiry = set.getInt("Expiry");
if (DATE < expiry) {
pipe.hset("donator_data", set.getString("UUID"), set.getString("Rank"));
} else {
// expire rank
}
}
DATE
is the amount of days that have passed in a year. This code is ran once at the start of the server, so even though it doesn't have to be too efficient, for peace of mind, I would like it to be.
I also considered using date objects and comparing them, realistically I only need two dates, expiry (day/month/year) and current (day/month/year) and then code something to compare them (e.g. if (expiryYear < year) || if (expiryMonth < month) etc.
Any other suggestions on how to overcome this issue?
Upvotes: 1
Views: 824
Reputation: 86324
The no doubt simplest is to use MySQL’s date
datatype for storing the expiration date.
LocalDate expiration = set.getObject("expiry", LocalDate.class);
LocalDate today = LocalDate.now(ZoneId.of("Europe/London"));
if (today.isBefore(expiration)) {
System.out.println("Fine");
} else {
System.out.println("Expired");
}
For storing the exipration date into the database:
LocalDate expiration = LocalDate.now(ZoneId.of("Europe/London")).plusDays(30);
yourPreparedStatement.setObject(3, expiration);
(assuming the expiration date should be substituted into the 3rd question mark in your SQL statement for saving).
Upvotes: 1