2

I need to know how to get current midnight from date.

For example I get "15.06.2012 16:40:20" and i need "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;

}
Mário Kapusta
  • 488
  • 7
  • 19

3 Answers3

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();
stefana
  • 2,606
  • 3
  • 29
  • 47
  • Not a good answer. Some dates in some time zones have no midnight because of Daylight Saving Time (DST) or other anomalies. See the [correct answer by Wabs](http://stackoverflow.com/a/21139689/642706). – Basil Bourque Jan 20 '14 at 00:06
6

Use JodaTime as such:

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

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

    ....

}
RobF
  • 2,758
  • 1
  • 20
  • 25
  • 1
    This is the best solution because for example in Brazil one day per year midnight does not exist. I am pretty sure that the OP has not thought about this detail, but maybe he is only concerned about local timestamps without time zone. – Meno Hochschild Jan 15 '14 at 14:16
  • This is good solution and I think that i will use this one, but I set as best solution @Nfear because his solution is without any external library. – Mário Kapusta Jan 15 '14 at 14:37
  • 2
    Personally I'd say avoiding Java Date and Calendar classes as much as possible is preferable ;) – RobF Jan 15 '14 at 14:45
  • Adding the [Joda-Time](http://www.joda.org/joda-time/) library is highly recommended. It is a high-quality well-worn library. In Java 8, the java.util.Date & .Calendar classes are being supplanted by new [java.time.* classes](http://download.java.net/jdk8/docs/api/java/time/package-summary.html) because of deficiencies. Those new classes were inspired by Joda-Time. Until you can move to Java 8, use Joda-Time. – Basil Bourque Jan 20 '14 at 00:11
2

You can use Calendar instance to get current year, month and day. then you can set the time whatever you want.

Calendar cal = Calendar.getInstance();
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
Ahmad Raza
  • 2,850
  • 1
  • 21
  • 37
  • 1
    They would like to set the time on the given date to midnight, not the current date. – RobF Jan 15 '14 at 14:10