Java Program to Display Dates of a Calendar Year in Different Format
As different countries do opt for different formats. So here the goal is simply to print dates of calendar in different years. The generic symbolic notation opted across the globe is:
Symbolic Notation Depicts y year M month in year d day in month E day of week
Concept: Whenever it comes down to the date and time the primary goal is to Date Class. It is necessary to be imported into our program.
Date Class was introduced in java in JDK version 1.0 but was later improved in JDK 1.1 by introducing Calendar Class. It deprecated most Calendar Class as 4 out of 6 constructors are marked as deprecated and most of the methods inside it. These two JDK are outdated now and hence known as legacy API. Finally, in 2014 in JDK8 new date/Time API was introduced. it includes java.time package which is now the main API for a date, time, instants, and duration.
Class Description Clock A clock providing access t the current instant, date, and time using a time zone Duration A time-based amount of time, such as ‘34.5 seconds’ Instant An instantaneous point on the time-line LocalDate A date without a time zine, calendar year such as 2007-12-03 LocalTime A time without a time zone in the calendar system MonthDay A month day in the calendar system OffsetTime A time with an offset from Greenwich in the calendar system Period A data-based amount of time in the calendar system Year A year in the calendar system ZonedDateTime A date with a time zone in a calendar system ZoneOffset A time zone offset from Greenwich
Package java.time.in JDK 8
There are different ways in which we can obtain the current date and time in java. Java doesn’t have a built-in Date class, though we can import java.time package to work with the time and date API. Some classes are as below:
- java.time.LocalDate– represents a date (year, month, day (yyyy-MM-dd)).
- java.time.LocalDateTime– represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns).
- java.time.format.DateTimeFormatter– formatter for displaying and parsing date-time objects.
When there is a need to display date and time in a different format, the ofPattern() method is used to accept all sorts of values. There are numerous formats that can be invoked later on can be mixed and match letters to achieve the required pattern.
Here the dealing will be with 3 types of formats:
- dd MMM yyyy
Below are the java programs for different date format.
Format 1: yyyy-MM-dd
Format 2: DD/MM/YY
Format 3: Day, dd MMM yyyy
Tuesday, 03 Nov 2020
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.