Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calendar Class in Java

Tags:

java

calendar

I am trying to print HOUR_OF_DAY,Minute and Second using Calendar Class. I used below command in my code.

  System.out.println(
      Calendar.HOUR+" "+
      Calendar.HOUR_OF_DAY+" "+
      Calendar.MINUTE+" "+
      Calendar.SECOND+" "
      );

It Gives output as below:

10 11 12 13 

Even when i ran this few hours back it gave same output.

I THOUGHT IT WILL PRINT CURRENT HOUR IN 24 HOUR FORMAT.But I am not getting that output.

So I want to know what this HOUR_OF_DAY, HOUR are supposed to print.

Please clarify.

like image 344
TheGraduateGuy Avatar asked May 03 '26 02:05

TheGraduateGuy


2 Answers

Calendar.HOUR, Calendar.HOUR_OF_DAY etc are just constants used to identify aspects of a date/time. They're typically used like this:

Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);

I can't easily think of any situation in which you'd want to print out the constants themselves.

Now even if you were using that, you'd still then be converting int values to String values via string concatenation - that has no idea about what format you want, because you're not specifying it explicitly. There's no such thing as a "2-digit-format int"... an int is just a number.

You should look into DateFormat and SimpleDateFormat - that's the preferred way to format dates and times using the standard Java class libraries. (I'd personally encourage you to look into Joda Time as a far better date/time API as well, but that's a different matter.)

For example:

DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
// Prints the current time using 24-hour format
System.out.println(formatter.format(new Date());
like image 162
Jon Skeet Avatar answered May 05 '26 16:05

Jon Skeet


try this

Calendar cal = Calendar.getInstance();

System.out.println(
  cal.get(Calendar.HOUR)+" "+
  cal.get(Calendar.HOUR_OF_DAY)+" "+
  cal.get(Calendar.MINUTE)+" "+
  cal.get(Calendar.SECOND)+" "
  );
like image 24
Pankaj Sharma Avatar answered May 05 '26 16:05

Pankaj Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!