Reputation: 59
I want to be able to bypass this code (getTimeInMillis()
in Calendar
class) and simply return the zero hour, minutes, and seconds from a specific date. Time is not set because it was built as a "Date" only now. So right now my code is always hitting this and giving me an "offset." This is even after doing below:
this.getEventDate().set(Calendar.HOUR_OF_DAY, 0);
I want to return milliseconds as long
. Right now it uses Calendar.getTimeInMillis()
which calculates a time as its not originally on the date object.
Is there a method out there to handle this?
Upvotes: 2
Views: 2730
Reputation: 56
If you want to get the number of milliseconds from a specified time to 00:00:00 of the day, the following code may help you
final long now = System.currentTimeMillis();
final long DAY_MILLIS = 1000 * 60 * 60 * 24;
//`now - (now % DAY_MILLIS)` will get the mill second at 08:00
long dayStart = now - (now % DAY_MILLIS) - DAY_MILLIS / 3;
long millisSinceStartOfToday = now - dayStart;
//in other word
//millisSinceStartOfToday = (now % DAY_MILLIS) + DAY_MILLIS / 3;
Upvotes: 0
Reputation: 338775
Your Question could use a rewrite for clarity. But I’ll take a guess at what you are asking.
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
You seem to be asking to determine the first moment of the day.
Understand that some dates in some time zones do not start at 00:00:00. So let java.time determine the first moment.
Here is an example. In Iran, the day of “Spring Ahead” in Daylight Saving Time starts at the stroke of midnight. The clock jumps to 1 AM. So the hour of 00:00:00 does not exist.
ZoneId z = ZoneId.of( "Asia/Tehran" ) ;
LocalDate ld = LocalDate.of( 2022 , Month.MARCH, 22 ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
See this code run live at IdeOne.com.
2022-03-22T01:00+04:30[Asia/Tehran]
And you apparently want to get a count of milliseconds from the epoch reference of first moment of 1970 as seen in UTC, an offset of zero hours-minutes-seconds.
Instant instant = zdt.toInstant() ; // Adjust from time zone to UTC by extracting an `Instant`.
long millis = instant.toEpochMilli() ;
1647894600000
Upvotes: 1
Reputation: 197
public static long millisSinceStartOfToday() {
Calendar date = new GregorianCalendar();
// reset hour, minutes, seconds and millis
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
return (new Date().getTime() - date.getTime().getTime());
}
Upvotes: 2