Javatpoint Logo
Javatpoint Logo

How to Convert Date into Character Month and Year Java?

There are numerous methods in Java for transforming a date into a character representation of the month and year. One typical method is to format the date using the SimpleDateFormat class in accordance with a predetermined pattern. Using the Calendar class to separate the month and year parts of the date and transform them into the corresponding character representations is an alternative method.

Use of the SimpleDateFormat Class

A subclass of the DateFormat class called SimpleDateFormat is used to format dates in a particular way. The format() function of a SimpleDateFormat object can be used to format a date so that it appears as a character representation of the month and year. Using the SimpleDateFormat class, the following code explains how to turn the date into a string that represents the contents of the month and year:

DateToStringExample.java

Output:

Mar 2023

In this example, the current date and time are used to construct a Date object. Next, we build a SimpleDateFormat object with the pattern "MMM yyyy," and we use that object's format() function to convert the date into a string representation of the month and year. "Mar 2023" or something similar will be the output of this programme.

Making Use of the Calendar

There are methods for dealing with dates and times in the abstract class known as the Calendar. The Calendar class may be used to extract the month and year components of a date and convert them to the relevant character representations. This will allow us to output a character representation of the month and year from a date. Using the Calendar class, the following code illustrates how to turn a date into a string representation of its month and year:

DateToStringExample.java

Output:

Mar 2023

In this example, we create a Date object with the current date and time, create a Calendar object with the current date and time, set its time to the date, extract the month component using the getDisplayName() method, extract the year component using the get() method, and then concatenate the month and year components into a string representation of the month and year. This programme will produce a result that looks somewhat like "Mar 2023."

Conclusion

Java programming frequently involves the challenge of converting a date into a character representation of the month and year. The calendar class can be used to separate the month and year components of the date and convert them to the relevant character representations, or the SimpleDateFormat class can be used to format the date in accordance with a predefined pattern. Both strategies are simple to understand and simple to apply.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA