0

To get the end time of the day.

Date now = new Date();
now.setHours(23);
now.setMinutes(59);
now.setSeconds(59);

To get the stat time of the day.

Date now = new Date();
now.setHours(00);
now.setMinutes(00);
now.setSeconds(00);
Simulant
  • 19,190
  • 8
  • 63
  • 98
devanathan
  • 768
  • 3
  • 10
  • 39
  • To be clear, you want a today's local date 1. set at midnight and 2. just before midnight at the end of the day? – Tunaki May 17 '16 at 08:56
  • What are you using this for? – aksappy May 17 '16 at 08:57
  • This looks pretty easy to me? Just wrap the code in some methods. – Rob Audenaerde May 17 '16 at 08:59
  • Looks easy, but isn't necessarily correct. The classic example of where this is wrong is in Asia/Gaza on the day daylight savings starts - there is no midnight. This is why Jodatime has the [`DateTime.withTimeAtStartOfDay()`](http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html#withTimeAtStartOfDay()) method. – Andy Turner May 17 '16 at 08:59
  • 1
    Also, days don't end at 23:59:59, they end at the instant the next day starts. But the last instant representable by a Java Date on a day is 23:59:59.999 (unless there is a leap second, of course). – Andy Turner May 17 '16 at 09:01
  • 1
    If you're using Java 8, you could use the `java.tome.LocalDate` class instead, that doesn't have a time notion. And from there, if you want a time, then use something like `LocalDate.now().atStartOfDay()` – Alexandre FILLATRE May 17 '16 at 09:04
  • Also relevant http://stackoverflow.com/questions/30293748/java-time-equivalent-of-joda-time-withtimeatstartofday-get-first-moment-of-t – Tunaki May 17 '16 at 09:07

1 Answers1

0

Date.set() methods are deprecated. Use Calendar instead.

Calendar cal = Calendar.getInstance();
Calendar start = new GregorianCalendar(cal.get(Calendar.YEAR),
    cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
Calendar end = new GregorianCalendar(cal.get(Calendar.YEAR),
    cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 23, 59, 59);

CLARIFICATION: A day does not end at 23:59:59. The above code just creates two Calendar instances, one set at 0:00:00 and the other one at 23:59:59 of the current day.

Lefteris008
  • 899
  • 3
  • 10
  • 29
  • Don't forget the milliseconds – Robert Kock May 17 '16 at 09:03
  • Just created two `Calendar` instances exactly as the OP indicated; the first one set at 0:00:00 and the other at 23:59:59. Declaring either of them as the "boundaries" of a certain day is completely wrong. Nonetheless, the OP can use any of the 7 constructor the `GregorianCalendar` class provides. – Lefteris008 May 17 '16 at 09:06