Hey everyone in my web application i am generating a verification code that is to be entered by user for account activation. I want that the generated verification code should be valid for specific time period say 12 hrs or 24 hrs. I am storing details of date and time when code is generated but how can i check for validity means suppose user entered code how can i check that he has entered code in validation period or not? How to compare date and time together? Thanks
Share
I wouldn’t think of it as a date and time as such. I’d think of it as an instant in time. When you generate the verification code, work out the instant in time “24 hours from now”, and store that. Then just check “the current instant” when you validate the verification code.
You could use
System.currentTimeMillis()to get the instant as alongvalue in milliseconds. (It’s since the Unix epoch, but that’s actually irrelevant here.) In fact, I’d suggest you create a kind ofClockinterface which can be used to determine the current instant, with an implementation usingSystem.currentTimeMillis()– or the Joda Time equivalent. That way you can unit test your code more easily.So take the current number of milliseconds, add your appropriate duration to it (again, in milliseconds), and that’s your expiry instant.