Java Tutorial2D Graphics in JavaJava Stack-Walking APIClass - Java ReflectionCommon Java PitfallsDocumenting Java CodeGenerating Java CodeInstalling Java (Standard Edition)Java AgentsJava Alternative CollectionsJava AnnotationsJava Apache Commons LangJava AppDynamics and TIBCO BusinessWorks Instrumentation for Easy IntegrationJava AppletsJava ArraysJava AssertingJava Atomic TypesJava AudioJava AutoboxingJava Basic Control StructuresJava BenchmarksJava BigDecimalJava BigIntegerJava Bit ManipulationJava BufferedWriterJava ByteBufferJava Bytecode ModificationJava C++ ComparisonJava Calendar and its SubclassesJava Character encodingJava Choosing CollectionsJava Classes and ObjectsJava ClassloadersJava Collection Factory MethodsJava CollectionsJava Command line Argument ProcessingJava Comparable and ComparatorJava Compiler - javacJava CompletableFutureJava Concurrent CollectionsJava Concurrent Programming (Threads)Java Console I/OJava ConstructorsJava Converting to and from StringsJava Creating Images ProgrammaticallyJava Currency and MoneyJava Date ClassJava Dates and Time (java.time.*)Java Default MethodsJava deploymentJava Dequeue InterfaceJava Disassembling and DecompilingJava Dynamic Method DispatchJava Editions, Versions, Releases and DistributionsJava EncapsulationJava Enum MapJava Enum starting with numberJava EnumsJava EnumSet classJava Exceptions and exception handlingJava Executor, ExecutorService and Thread poolsJava ExpressionsJava File I/OJava FileUpload to AWSJava Floating Point OperationsJava Fluent InterfaceJava FTP (File Transfer Protocol)Java Functional InterfacesJava GenericsJava Getters and SettersJava HashtableJava HttpURLConnectionJava Immutable ClassJava Immutable ObjectsJava InheritanceJava InputStreams and OutputStreamsJava InterfacesJava Iterator and IterableJava JavaBeanJava JAX-WSJava JAXBJava JMXJava JNDIJava JShellJava Just in Time (JIT) compilerJava JVM FlagsJava JVM Tool InterfaceJava Lambda ExpressionsJava LinkedHashMapJava List vs SET

Java Calendar and its Subclasses

From WikiOD

Remarks[edit | edit source]

As of Java 8, Calendar and its subclasses have been superseded by the java.time package and its subpackages. They should be preferred, unless a legacy API requires Calendar.

Creating Calendar objects[edit | edit source]

Calendar objects can be created by using getInstance() or by using the constructor GregorianCalendar.

It's important to notice that months in Calendar are zero based, which means that JANUARY is represented by an int value 0. In order to provide a better code, always use Calendar constants, such as Calendar.JANUARY to avoid misunderstandings.

Calendar calendar = Calendar.getInstance();
Calendar gregorianCalendar = new GregorianCalendar();
Calendar gregorianCalendarAtSpecificDay = new GregorianCalendar(2016, Calendar.JANUARY, 1);
Calendar gregorianCalendarAtSpecificDayAndTime = new GregorianCalendar(2016, Calendar.JANUARY, 1, 6, 55, 10);

Note: Always use the month constants: The numeric representation is misleading, e.g. Calendar.JANUARY has the value 0

Increasing / Decreasing calendar fields[edit | edit source]

add() and roll() can be used to increase/decrease Calendar fields.

Calendar calendar = new GregorianCalendar(2016, Calendar.MARCH, 31); // 31 March 2016

The add() method affects all fields, and behaves effectively if one were to add or subtract actual dates from the calendar

calendar.add(Calendar.MONTH, -6);

The above operation removes six months from the calendar, taking us back to 30 September 2015.

To change a particular field without affecting the other fields, use roll().

calendar.roll(Calendar.MONTH, -6);

The above operation removes six months from the current month, so the month is identified as September. No other fields have been adjusted; the year has not changed with this operation.

Finding AM/PM[edit | edit source]

With Calendar class it is easy to find AM or PM.

  Calendar cal = Calendar.getInstance();
  cal.setTime(new Date());
  if (cal.get(Calendar.AM_PM) == Calendar.PM)
      System.out.println("It is PM");

Subtracting calendars[edit | edit source]

To get a difference between two Calendars, use getTimeInMillis() method:

Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c2.set(Calendar.DATE, c2.get(Calendar.DATE) + 1);

System.out.println(c2.getTimeInMillis() - c1.getTimeInMillis()); //outputs 86400000 (24 * 60 * 60 * 1000)