Android-获取一天开始和结束的Unix时间戳 [英] Android - Get Unix time stamp for beginning and end of day

查看:637
本文介绍了Android-获取一天开始和结束的Unix时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SQLite数据库,该数据库的整数列用于存储unix时间戳,我需要能够查询此列的特定日期.

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.

我正在寻找一种方法来返回给定日期的开始和结束的Unix时间.做这个的最好方式是什么?

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?

推荐答案

这是一种实现方法.

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

这篇关于Android-获取一天开始和结束的Unix时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆