【问题标题】:Android - Get Unix time stamp for beginning and end of dayAndroid - 获取一天的开始和结束的 Unix 时间戳
【发布时间】:2015-03-29 03:24:54
【问题描述】:

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

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

【问题讨论】:

  • 认为阅读this 会有所帮助。考虑 Calendar set() 方法。

标签: java android datetime time android-calendar


【解决方案1】:

这是一种方法。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2020-09-25
    相关资源
    最近更新 更多