I would like to get the current date in milliseconds with only year, month and date. But when I use this code:
Calendar cal = Calendar.getInstance();
cal.clear(Calendar.HOUR);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
currentDate = cal.getTimeInMillis();
I still get the time in milliseconds with the hour. How can I fix this?
Be carefull on the timezone of your Calendar.
tl;dr
LocalDate
If what you want is actually just the date without the time, use
LocalDate
class.The
LocalDate
class represents a date-only value without time-of-day and without time zone.A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of
continent/region
, such asAmerica/Montreal
,Africa/Casablanca
, orPacific/Auckland
. Never use the 3-4 letter abbreviation such asEST
orIST
as they are not true time zones, not standardized, and not even unique(!).ZonedDateTime
If you want a date with the time-of-day set to the first moment of the day, ask java.time to determine that moment for you. Do not assume the first moment is at 00:00:00. Anomalies such as Daylight Saving Time means first moment may occur at some other time such as 01:00:00.
Use that time zone object, the
ZoneId
, to generate aZonedDateTime
object.To view this same moment as a value in UTC, extract a
Instant
object.Avoid legacy date-time classes
Avoid the troublesome old date-time classes such as
Calendar
. These are now legacy, supplanted by the java.time classes.About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
,Calendar
, &SimpleDateFormat
.The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.from the javadoc: The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and the the resolution rule for the time of day is applied. Clearing one of the fields doesn't reset the hour of day value of this Calendar. Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value.
might need to set AM/PM as well
If you only want this relative to GMT and explicitly just want milliseconds, you can use this:
If you want to use Joda time: