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);
7
  • 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
    Commented May 17, 2016 at 8:56
  • What are you using this for?
    – aksappy
    Commented May 17, 2016 at 8:57
  • This looks pretty easy to me? Just wrap the code in some methods. Commented May 17, 2016 at 8: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). Commented May 17, 2016 at 9: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() Commented May 17, 2016 at 9:04

1 Answer 1

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.

2
  • Don't forget the milliseconds Commented May 17, 2016 at 9: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. Commented May 17, 2016 at 9:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.