Home » Java » java – How to set multiple attributes for calender object at once?-Exceptionshub

java – How to set multiple attributes for calender object at once?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

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.000A.M.

How to&Answers:

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()));

Answer:

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();

Answer:

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