'How to set multiple attributes for calender object at once?
This is my existing code snippet:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
I just want to assign those attributes at once, something like:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND, 0);
I am not sure it is possible or not, because I am new to java. Please help me if there is other way around to achive this.
If possible, please give others solutions also. Objective is to set the given cal
object to 00:00:00.000
A.M.
Edit 1: I think this question was clear and understandable. Please consider upvoting as I couldn't ask anymore questions on stackoverflow.
Solution 1:[1]
The old Calendar class can be set by the current generation of java time classes:
// Current time classes:
LocalDate today = LocalDate.now();
// LocalDate today = LocalDate.of(2020, 2, 18);
LocalDateTime morning = today.atStartOfDay();
// Old classes:
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(morning.toEpochSecond()));
Solution 2:[2]
If possible, avoid the use of the legacy Calendar
class. Do use the classes from the java.time package, e.g.:
LocalDateTime todayAtStartOfDay = LocalDate.now().atStartOfDay();
But if Calendar
must be used, then consider using Calendar.Builder
, e.g,:
Calendar cal = new Calendar.Builder()
.setTimeOfDay(0, 0, 0, 0) // hour, minute, second, millis
.build();
Solution 3:[3]
There is an overloaded set
method in the Calendar
class:
void java.util.Calendar.set(int year, int month, int date, int hourOfDay, int minute, int second)
Unfortunately you have to set your milliseconds manually. And you also have to use date formatter. Here an example
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS aa");
Calendar cal = Calendar.getInstance();
cal.set(0, 0, 0, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(sdf.format(cal.getTime()));
It returns 00:00:00.000 AM
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Joop Eggen |
Solution 2 | Andrew S |
Solution 3 | Planck Constant |