如何获得给定日期的午夜?

时间:2014-01-15 14:01:36

标签: java date

我需要知道如何从目前的午夜开始。

例如我得到“15.06.2012 16:40:20”,我需要“15.06.2012 00:00:00”。

public List<Game> getGamesByDate(Date day) throws SQLException {

    final Date startDate = day;

    //here I need to convert startDate to midnight somehow

    final Date endDate = new Date(day.getTime() + (23 * HOUR) + (59 * MINUTE));
    final List<Game> games = gameDAO.getGamesByDate(startDate, endDate);

    return games;

}

3 个答案:

答案 0 :(得分:7)

Date startDate = day;
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
Date newDate = cal.getTime();

答案 1 :(得分:6)

使用JodaTime

public List<Game> getGamesByDate(Date day) throws SQLException {

    final DateTime startDate = new DateTime(day).withTimeAtStartOfDay();

    ....

}

答案 2 :(得分:2)

您可以使用日历实例获取当前年,月和日。然后你可以随心所欲地设定时间。

Calendar cal = Calendar.getInstance();
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);