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

Már*_*sta 2 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;

}
Run Code Online (Sandbox Code Playgroud)

ste*_*ana 8

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();
Run Code Online (Sandbox Code Playgroud)


Rob*_*obF 6

使用JodaTime如下:

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

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

    ....

}
Run Code Online (Sandbox Code Playgroud)

  • 我个人认为尽可能避免使用Java Date和Calendar类是可取的;) (2认同)