2012-07-18 3 views
3

Android 앱에서 마지막 가져 오기 후 X 시간 이상 지난 경우에만 데이터를 다시 가져오고 싶습니다.현재 시간이 "last_updated"시간에서 1 시간 이상인지 확인하십시오.

나는 형식으로 내 SQLite 데이터베이스에 LAST_UPDATED 시간을 저장하고 있습니다 : 2012/07/18 00:01:40

이 어떻게 그런 "그때부터 시간"또는 무언가를 얻을 수 있나요? 지금까지

내 코드 :

package com.sltrib.utilities; 

import java.text.SimpleDateFormat; 
import java.util.Calendar; 

public class DateHelper 
{ 

    public static String now() 
    { 
     Calendar currentDate = Calendar.getInstance(); 
     SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
     String dateNow = formatter.format(currentDate.getTime()); 
     //System.out.println("Now the date is :=> " + dateNow); 
     return dateNow; 
    } 

    public static int hoursAgo(String datetime) 
    { 
     //return the number of hours it's been since the given time 
     //int hours = ?? 
     //return hours; 
    } 

} 
+0

당신은 MS의 시간을 저장할 수 있습니다. 그런 다음 차이점을 계산하고 시간당 mmilliseconds 수로 나눠야합니다. – Weeman

답변

6

Calendar의 또는 Date의 사이에 수학을 할 것입니다.

참고 : 양방향는 다음과 같습니다. Calendar!

여기 Date를 사용하는 예제입니다 :

public static int hoursAgo(String datetime) { 
    Date date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.ENGLISH).parse(datetime); // Parse into Date object 
    Date now = Calendar.getInstance().getTime(); // Get time now 
    long differenceInMillis = now.getTime() - date.getTime(); 
    long differenceInHours = (differenceInMillis)/1000L/60L/60L; // Divide by millis/sec, secs/min, mins/hr 
    return (int)differenceInHours; 
} 

이 여기에 포함 된 일부 try/catch 블록 (당신은 아마 throws으로 처리해야하는)하지만 이것은 기본적인 생각이다.

편집는 :

public static int hoursAgo(String datetime) { 
    Calendar date = Calendar.getInstance(); 
    date.setTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.ENGLISH).parse(datetime)); // Parse into Date object 
    Calendar now = Calendar.getInstance(); // Get time now 
    long differenceInMillis = now.getTimeInMillis() - date.getTimeInMillis(); 
    long differenceInHours = (differenceInMillis)/1000L/60L/60L; // Divide by millis/sec, secs/min, mins/hr 
    return (int)differenceInHours; 
} 
+0

죄송합니다. getTime()이어야합니다. 위의 게시물을 수정했습니다. – Eric

+0

감사합니다 - 이것은 작동하고 있다고 생각합니다 - 아침에 두 번 확인하고 답장/표시/업데이트 ... 등 – Dave

+0

90 분이 돌아 오는지 확실하지 않았으므로 분으로 변경했습니다 (그리고 60과 비교). 1 또는 2 시간 ... 등. 그래서 .. 그냥 마지막 60L을 제거하고 가서 좋은가 - 그것은 작동합니다! 감사! – Dave

관련 문제