0

I want to insert expiration date in Redis based on TTL. How can I count the expiration date?

I'm trying to use TimeCategory class, here is the example:

def ttl = 3600;
def date = new Date()

TimeDuration duration = getSeconds(ttl) 

TimeDuration expiryDate = date.plus.duration

Is that a correct approach to expiry date counting?

Leocete
  • 195
  • 2
  • 15

1 Answers1

2

Overcomplicated if you ask me.

One-liner should be sufficient here:

Date expiryDate = new Date( System.currentTimeMillis() + ttlInSeconds * 1000l )

Make sure you are using long numbers here, otherwise the numbers will be cut down to 2147483647 which might lead to wrong results for large TTLs.

injecteer
  • 20,038
  • 4
  • 45
  • 89
  • should I import groovy time: `import groovy.time.*` ? – Leocete Apr 05 '19 at 09:08
  • no additional imports needed, it's plain `java.util` – injecteer Apr 05 '19 at 09:09
  • will this solution also work with seconds? cause `ttl` is the amount of second and I could see you used `currentTimeMillis()` method – Leocete Apr 05 '19 at 09:09
  • it is counting, but shows a wrong data, for ex. if `ttl = 13140000` (5 month), the expiry date shows: Mon Apr 08 11:07:37 EEST 2019 – Leocete Apr 05 '19 at 09:16
  • it's because you use `int` by default instead of `long`. then it would give you `Wed Sep 04 11:19:26 GMT 2019`. See the update – injecteer Apr 05 '19 at 09:18
  • Everything is working! Thank you very much! Can you explain please, why it didn't work with `int` but worked with `long` - the amount of number exceeds `int` length? – Leocete Apr 05 '19 at 09:21
  • 1
    `Integer.MAX_VALUE` == `2147483647`, so if the inteded value is greater then that, it would be cut down. – injecteer Apr 05 '19 at 09:22