2013-03-07 9 views
1

MVC 패턴을 사용하여 Java EE에 간단한 로그인 프로그램을 작성 중이며 비밀번호가 1 년 넘었 음을 사용자에게 알리고 싶습니다. 현재 데이터베이스에서 데이터를 가져 와서 문자열로 변환 할 수 있지만 그 이후에는 현재 날짜와 비교하는 방법을 알지 못합니다. java에서 현재 날짜와 MySQL을 비교하는 방법은 무엇입니까?

내가 지금까지 무엇을 가지고 :

public String validateAccount(String email, String enterPassword) { 

     try { 
      Class.forName(driverName).newInstance(); 
     } catch (InstantiationException | IllegalAccessException 
       | ClassNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     Connection connection; 

     try { 

      connection = DriverManager.getConnection(dbURL, username, password); 

      // Retrive current user data from database 
      String getCredentials = "SELECT id,dateSet,strength FROM users WHERE email=? AND hashPassword=SHA2(CONCAT(?, salt), 256)"; 
      PreparedStatement verifyCredentials = connection 
        .prepareStatement(getCredentials); 
      verifyCredentials.setString(1, email); 
      verifyCredentials.setString(2, enterPassword); 
      ResultSet foundData = verifyCredentials.executeQuery(); 

      while (foundData.next()) { 
       System.out.println("Found account"); 
       int id = foundData.getInt("id"); 
       String dateSet = foundData.getString("dateSet"); 
       String strength = foundData.getString("strength"); 

       // ... do something with these variables ... if 
       if (strength.equals("Weak")) { 
        return "1"; 

       } else if (/*Check if the date in the database is over a year old, and return 2*/) { 
        return "2"; 
       } else { 
        return "0"; 
       } 

      } 
      foundData.close(); 

      return "Account not found, re-enter your info again"; 

     } catch (SQLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     return ""; 

    } 

답변

3

대신) foundData.getTimestamp를 (사용하고, 일반 자바 데이터 클래스로 변환 할 수있는 타임 스탬프를 얻을 수 있습니다 :

당신은 당신이 직접의 체크를 할 수있다 (당신은뿐만 아니라 달력을 사용해야합니다) 날짜 인스턴스 작업에 익숙하지 않은 경우 그래서, 당신은 대안

Date dateSet = new Date(foundData.getTimestamp("dateSet").getTime()); 

또는 같은 것을 할 것이다 당신의 SQL 쿼리,

String getCredentials = "SELECT id,dateSet,strength, IF(dateSet < NOW() - INTERVAL 1 YEAR, TRUE, FALSE) AS oldPasswd FROM users WHERE email=? AND hashPassword=SHA2(CONCAT(?, salt), 256)"; 

다음

else if (foundData.getBoolean("oldPasswd")) { 
    return "2"; 
} 
+0

나는 .getTimestamp() 메소드 또는 일반적으로 날짜와 familizarized 아니에요의 차이를 받게됩니다. 어떤 형식의 .getTimestamp가 반환되며 어떻게 변환합니까? –

+0

데이터베이스의 열이 DATE 유형이라는 가정하에 작업하면 gettimestamp는 Timestamp의 인스턴스를 반환합니다.이 인스턴스는 unixepoc 이후의 밀리 초 수를 long으로 제공 할 수 있습니다. Date 클래스에는 Unixepoc이 param 이후로 밀리 초 수를 나타내는 long을 취하는 생성자가 있으므로 날짜 인스턴스를 얻을 수 있습니다. – JustDanyul

+0

여러분! 나는 그것이 효과가 있다고 생각한다. : D –

2

난 그냥 당신이 결과 집합을 형성 날짜에 액세스 한 방식을 수정이

java.sql.Date date = foundData.getDate("dateSet"); 
java.sql.Date date2 = new Date(System.currentTimeMillis()); 
date2.compareTo(date); 

을 시도합니다. "compareTo"는 Date 인수가이 Date와 같으면 값 0을 반환한다는 점에 유의하십시오. 이 Date가 Date 인수보다 앞이면 0보다 작은 값. 이 Date가 Date 인수보다 뒤에 있으면 0보다 큰 값

다음 방법은 당신에게 일

public static long daysBetween(Date sd, Date ed) { 
    Calendar startDate = Calendar.getInstance(); 
    startDate.setTime(sd); 
    Calendar endDate = Calendar.getInstance(); 
    startDate.setTime(ed); 
    Calendar date = (Calendar) startDate.clone(); 
    long daysBetween = 0; 
    while (date.before(endDate)) { 
     date.add(Calendar.DAY_OF_MONTH, 1); 
     daysBetween++; 
    } 
    return daysBetween; 
} 
+0

나는 그것을 이해합니다. 그러나 일단 두 날짜를 얻으면 365 일 (1 년) 이상의 차이가 있는지 어떻게 확인합니까? –

+0

일일 차이를 줄 수있는 방법으로 내 대답을 업데이트했습니다 예 : – kunal

+0

+1 : – JustDanyul

관련 문제