In my code I need to find all my things that happened today. So I need to compare against dates from today at 00:00am (midnight early this morning) to 12:00pm (midnight tonight).
I know ...
Date today = new Date();
... gets me right now. And ...
Date beginning = new Date(0);
... gets me zero time on Jan 1, 1970. But what's an easy way to get zero time today and zero time tomorrow?
UPDATE; I did this, but surely there's an easier way?
Calendar calStart = new GregorianCalendar();
calStart.setTime(new Date());
calStart.set(Calendar.HOUR_OF_DAY, 0);
calStart.set(Calendar.MINUTE, 0);
calStart.set(Calendar.SECOND, 0);
calStart.set(Calendar.MILLISECOND, 0);
Date midnightYesterday = calStart.getTime();
Calendar calEnd = new GregorianCalendar();
calEnd.setTime(new Date());
calEnd.set(Calendar.DAY_OF_YEAR, calEnd.get(Calendar.DAY_OF_YEAR)+1);
calEnd.set(Calendar.HOUR_OF_DAY, 0);
calEnd.set(Calendar.MINUTE, 0);
calEnd.set(Calendar.SECOND, 0);
calEnd.set(Calendar.MILLISECOND, 0);
Date midnightTonight = calEnd.getTime();
The simplest way with JodaTime
DateMidnight date = DateMidnight.now();
Old fashioned way..
I did this differently than everyone else here did. I'm new to Java, so maybe my solution is poor.
I'm not sure this works yet, but either way, I'd appreciate any feedback on this solution.
I'm confused by the statement above that you can calculate tomorrow by calling:
If you add 1 to the day of the month and it's the 31st day, don't you get the 32nd day of the month?
Why are times/dates not all based on UTC in Java? I would think Timezones should only be needed when used with i/o, but internally should always be used in UTC. However, the classes seem to include Timezone info which seems not only wasteful, but prone to coding errors.
I know this is very old post. I thought to share my knowledge here !
For the date Mid night today with exact Time zone you can use following
Where
(1000*60 * 330)
is being subtracted i.e. actually related to time zone for example Indian time zone i.e. kolkata differs +5:30hrs from actual . So subtracting that with converting into milliseconds.So change last substracted number according to you. I m creating a product i.e. only based in India So just used specific timestamp.
But beware that
java.sql.Date.toInstant()
always throwsUnsupportedOperationException
.Via LocalDate to java.util.Date and vice versa simpliest conversion?
This appears to be an option:
to add a day to it, either
or
I have a hunch the latter is preferred in case of something weird like daylight savings causing adding 24 hours to not be enough (see https://stackoverflow.com/a/4336131/32453 and its other answers).