2015-01-29 1 views
0

유닉스 타임 스탬프를 저장하는 정수 컬럼을 가진 SQLite 데이터베이스가 있고 특정 날짜에이 열을 쿼리 할 수 ​​있어야합니다.안드로이드 - 시작과 끝날 때 유닉스 타임 스탬프 받기

나는 주어진 날의 시작과 끝의 유닉스 시간을 반환하는 방법을 찾고있다. 이 작업을 수행하는 가장 좋은 방법은 무엇입니까?

+0

[this] (http://developer.android.com/reference/java/util/Calendar.html)가 도움이 될 것이라고 생각하십시오. Calendar set() 메소드를 고려하십시오. – ivkil

답변

8

여기 한 가지 방법이 있습니다. 특정 날짜의 시간을 원하는 경우

public long getStartOfDayInMillis() { 
    Calendar calendar = Calendar.getInstance(); 
    calendar.set(Calendar.HOUR_OF_DAY, 0); 
    calendar.set(Calendar.MINUTE, 0); 
    calendar.set(Calendar.SECOND, 0); 
    calendar.set(Calendar.MILLISECOND, 0); 
    return calendar.getTimeInMillis(); 
} 

public long getEndOfDayInMillis() { 
    // Add one day's time to the beginning of the day. 
    // 24 hours * 60 minutes * 60 seconds * 1000 milliseconds = 1 day 
    return getStartOfDayInMillis() + (24 * 60 * 60 * 1000); 
} 

, 당신은 그것을 처리하는 코드를 수정할 수 있습니다.

/** 
* @param date the date in the format "yyyy-MM-dd" 
*/ 
public long getStartOfDayInMillis(String date) throws ParseException { 
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
    Calendar calendar = Calendar.getInstance(); 
     calendar.setTime(format.parse(date)); 
    calendar.set(Calendar.HOUR_OF_DAY, 0); 
    calendar.set(Calendar.MINUTE, 0); 
    calendar.set(Calendar.SECOND, 0); 
    calendar.set(Calendar.MILLISECOND, 0); 
    return calendar.getTimeInMillis(); 
} 

/** 
* @param date the date in the format "yyyy-MM-dd" 
*/ 
public long getEndOfDayInMillis(String date) throws ParseException { 
    // Add one day's time to the beginning of the day. 
    // 24 hours * 60 minutes * 60 seconds * 1000 milliseconds = 1 day 
    return getStartOfDayInMillis(date) + (24 * 60 * 60 * 1000); 
}