I basically want to get zero or beginning hour for currrent day.
def today = Calendar.instance
today.set(Calendar.HOUR_OF_DAY, 0)
today.set(Calendar.MINUTE, 0)
today.set(Calendar.SECOND, 0)
println today // Mon Mar 15 00:00:00 SGT 2010
Use the setUTCHours() method to get the start and end of the day, e.g. startOfDay. setUTCHours(0, 0, 0, 0) . The method takes the hours, minutes, seconds and milliseconds as parameters and sets them for the specified date according to universal time.
The Clock. systemUTC(). instant() method returns the current date and time both.
LocalDateTime startOfDay = LocalDateTime. of(localDate, LocalTime. MIDNIGHT);
From a LocalDate Object First of all, let's see how we can get the start or end of a day given to us as a LocalDate object, such as: The simplest way of getting a LocalDateTime representing the beginning of a particular day is by using the atStartOfDay () method:
If you want the entire day of a date as seen in UTC rather than in a time zone, use OffsetDateTime. LocalDate today = LocalDate.now ( ZoneOffset.UTC ) ; OffsetDateTime odtStart = today.atTime ( OffsetTime.MIN ) ; OffsetDateTime odtStop = today.plusDays ( 1 ).atTime ( OffsetTime.MIN ) ;
When a shop is open from 8AM to 6PM, the end time displayed is 6PM, not 5:59:59 PM. But there is no built-in method. As commented by @JBNizet, if you want to create an interval, you can also use an interval up to midnight, exclusive. What about daylight saving time? @MateusViccari LocalDate / LocalDateTime have no time zone so no DST rule.
To get the first moment of the day go through the LocalDate class and its atStartOfDay method. ZonedDateTime zdtStart = zdt.toLocalDate ().atStartOfDay ( zoneId ); Using Half-Open approach, get first moment of following day. ZonedDateTime zdtTomorrowStart = zdtStart.plusDays ( 1 );
Not simpler than the other solutions, but less lines:
def now = new GregorianCalendar()
def today = new GregorianCalendar(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH))
println today.getTime()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With