Use the date-time API.
The below code uses class java.time.LocalDateTime
to store the expiry date of the coupon. I changed class Discount
to a record. I added a [static] member start
for generating the expiry dates for the generated coupons. Simply call method plusHours to add 24 hours. Method main
, in the below code, calls method generateCouponCode
twice to demonstrate that the expiry date in the first generated coupon is the current time plus 24 hours and the second generated coupon's expiry date is 48 hours after the current time.
import java.time.LocalDateTime;
public record Discount(String coupon, LocalDateTime expires) {
private static LocalDateTime start = LocalDateTime.now();
public static Discount generateCouponCode() {
String mycouponPattern = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuffer stringBuffer = new StringBuffer(10);
for (int i = 0; i < 10; i++) {
int indexVal = (int) (mycouponPattern.length() * Math.random());
stringBuffer.append(mycouponPattern.charAt(indexVal));
}
System.out.println("Coupon code generated successfully....");
start = start.plusHours(24L);
Discount coupon = new Discount(stringBuffer.toString(), start);
return coupon;
}
public static void main(String[] args) {
System.out.println(Discount.generateCouponCode());
System.out.println(Discount.generateCouponCode());
}
}
以上代码的样例运行的输出:
Coupon code generated successfully....
Your Generated coupon code is:Q8HW5AIGHQ
Discount[coupon=Q8HW5AIGHQ, expires=2023-10-29T10:18:23.564755300]
Coupon code generated successfully....
Your Generated coupon code is:HEX57DHAE0
Discount[coupon=HEX57DHAE0, expires=2023-10-30T10:18:23.564755300]
EDIT
作为对OP comment的响应,以下代码将优惠券生成限制为仅在最后生成的优惠券过期后生成.
import java.time.LocalDateTime;
public record Discount(String coupon, LocalDateTime expires) {
private static LocalDateTime start = LocalDateTime.now();
public static Discount generateCouponCode() {
if (LocalDateTime.now().isAfter(start)) {
String mycouponPattern = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuffer stringBuffer = new StringBuffer(10);
for (int i = 0; i < 10; i++) {
int indexVal = (int) (mycouponPattern.length() * Math.random());
stringBuffer.append(mycouponPattern.charAt(indexVal));
}
System.out.println("Coupon code generated successfully....");
start = start.plusHours(24L);
Discount coupon = new Discount(stringBuffer.toString(), start);
return coupon;
}
else {
throw new UnsupportedOperationException("Next coupon can be generated after: " + start);
}
}
public static void main(String[] args) {
System.out.println(Discount.generateCouponCode());
System.out.println(Discount.generateCouponCode());
}
}
运行上面的代码会产生以下输出:
Coupon code generated successfully....
Discount[coupon=TK7SWLHMBM, expires=2023-10-29T12:23:36.342781700]
Exception in thread "main" java.lang.UnsupportedOperationException: Next coupon can be generated after: 2023-10-29T12:23:36.342781700
at basetest.Discount.generateCouponCode(Discount.java:22)
at basetest.Discount.main(Discount.java:28)