1

I have written a code for verification through email by sending otp. I have to configure in such a way that if the user enters the otp after 4 hours it should not be accepted. I have used date object with if conditions and it works fine but is there any way to achieve same in less coding.

Date dateFromDatabase=emailData.getBody().getUpdated();

if((dateFromDatabase.getYear()-date.getYear())==0){

    if((dateFromDatabase.getMonth()-date.getMonth())==0){

        if((dateFromDatabase.getDay()-date.getDay())==0){
            if((dateFromDatabase.getHours()-date.getHours())<=4){
                System.out.print("May Be Right otp");

                if( emailData.getBody().getHASHCODE().equals(fromotp)){
                    System.out.print("matched");
                    emails.setId(emailData.getBody().getId());
                    emails .setVERIFIED(1);
                    emails.setHASHCODE("");
                    emails.setEmails(To);
                    //updateEmails(emails);
                    String Subject="Pharmerz Thanknote";
                    String Acknowledge="Thank you for verifying on Pharmerz";
                    email.SendMail(To,Subject,Acknowledge);
                    Emails saveEmails =emailService.create( emails );
                    return new ResponseEntity<Emails>(emails,HttpStatus.OK);

                }else{
                    System.out.print("miss matched");
                    emailService.delete(emailData.getBody().getId());
                    return new ResponseEntity<Emails>(HttpStatus.BAD_REQUEST);
                }



            }else{
                System.out.print("Wrong or Old Otp");
                emailService.delete(emailData.getBody().getId());
                return new ResponseEntity<Emails>(HttpStatus.BAD_REQUEST);
            }
        }else{
            System.out.print("Wrong or Old Otp");
            emailService.delete(emailData.getBody().getId());
            return new ResponseEntity<Emails>(HttpStatus.BAD_REQUEST);
        }

    }else{
        System.out.print("Wrong or Old Otp");
        emailService.delete(emailData.getBody().getId());
        return new ResponseEntity<Emails>(HttpStatus.BAD_REQUEST);
    }

}
else{
    System.out.print("Wrong or Old Otp");
    emailService.delete(emailData.getBody().getId());
    return new ResponseEntity<Emails>(HttpStatus.BAD_REQUEST);
}
Mikhail Antonov
  • 1,297
  • 3
  • 21
  • 29
Amit Gujarathi
  • 1,090
  • 1
  • 12
  • 25

2 Answers2

2

Try this :

Date currentDate = new Date();
Date dateFromDatabase = // get the date from the database

long duration  = dateFromDatabase.getTime() - currentDate.getTime();
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);

You can use the diffInHours variable and perform your business logic.

Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Apr 26 '17 at 20:40
1

tl;dr

Duration.between(                      // Span-of-time unattached to timeline.
    myUtilDate.toInstant() ,           // Convert legacy java.util.Date object to modern java.time.Instant.
    Instant.now()                      // Get the current moment.
).compareTo( Duration.ofHours( 4 ) )   // Ask if the time span variance exceeds our limit of four hours.

Avoid legacy date-time classes.

I assume your Date object at top of code is a java.util.Date. That class is part of the troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

Using java.time

Instant

Convert that Date to its modern equivalent: Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant then = myUtilDate.toInstant();

Apparently you want to compare this against the current moment and look for a four-hour variance, though your Question is not clear.

Get the current moment is simple.

Instant now = Instant.now();

Duration

Represent a span of time unattached to the timeline as a Duration.

Duration variance = Duration.between( then , now );

Check for a negative duration, meaning the past moment is actually showing as future.

if( variance.isNegative() ) { … handle error condition … }

Compare that duration to our limit of 4 hours. If the time span between then and now is over four hours, compareTo returns a positive number (number greater than zero).

Duration limit = Duration.ofHours( 4 );
Boolean exceededLimit = ( variance.compareTo( limit ) > 0 ) ; // If the time span between then and now is over four hours, `compareTo` returns a positive number (number greater than zero). 

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154