Android - Get Unix time stamp for beginning and en

2019-09-03 16:16发布

I have an SQLite database that has an integer column to store a unix time stamp and I need to be able to query this column for specific days.

I am looking for a method to return the Unix time for the beginning and end of a given day. What is the best way to do this?

1条回答
我只想做你的唯一
2楼-- · 2019-09-03 17:13

Here is one way to do it.

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);
}

If you want the times for a specific date, you can modify the code to handle that.

/**
 * @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);
}
查看更多
登录 后发表回答