This article uses different methods to format months using different libraries and corresponding import statements in the Java language. There are many ways to display months in Java program output. Sometimes months are written as numbers, sometimes months are written in long or abbreviated form. Month names can also be written in other languages, such as Spanish, French, etc.
algorithm
Step 1 - Ask the user to enter a date.
Step 2 - Determine the month part of the date.
Step 3 - Specify the month format.
Step 4 - Print the month in the specified format.
Multiple methods
We provide solutions using different methods.
By using java.time.Month
By using java.util.Date and arrays
By using String and its methods
By using java.text.SimpleDateFormat
By using java.util.Calendar
Let’s look at the program and its output one by one.
Method 1: Using java.time.Month
In this method, the month is printed by specifying the month number starting from the number 1. For example -> Month.of(1) will give JANUARY.
Example
import java.time.Month; public class ShowMonth { public static void main(String[] args) { Month mon; for (int mn=1; mn<=12; mn++){ // The first month starts with number 1 mon = Month.of(mn); System.out.println(mon); } } }
Output
JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER
Method 2: Using java.util.Date and arrays
In this method, the string array is used to store the short form of the month, such as Jan, Feb, etc. Use the substring method to identify the month part of the date and print it in the specified format.
Example
import java.util.Date; public class ShowMonth11{ public static void main(String[] args) { // Months are stored as arrays String[] st_arr={"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep","Oct","Nov","Dec"}; String[] seq_arr={"First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth","Tenth","Eleventh","Twelfth"}; // Fetch the current date Date dt = new Date(); String dtstr= dt.toString(); // printing the months for (int mn=0; mn<12; mn++){ System.out.println("The Number " + seq_arr[mn]+ " month in the year is : " +st_arr[mn]); } //selecting the month part from the date String substr2 = dtstr.substring(4,7); System.out.println("\nThe Time now is " + dt); System.out.println("\nThe current month is " + substr2); } }
Output
The Number First month in the year is : Jan The Number Second month in the year is : Feb The Number Third month in the year is : Mar The Number Fourth month in the year is : Apr The Number Fifth month in the year is : May The Number Sixth month in the year is : Jun The Number Seventh month in the year is : Jul The Number Eighth month in the year is : Aug The Number Ninth month in the year is : Sep The Number Tenth month in the year is : Oct The Number Eleventh month in the year is : Nov The Number Twelfth month in the year is : Dec The Time now is Fri Feb 24 13:19:06 IST 2023 The current month is Feb
Method 3: Using strings and their methods
In this method, the date is input as a string. Then use the substring method to identify and print the month part. Months can be displayed even in numeric form.
Example
public class ShowMonth22{ public static void main(String[] args) { String dtstr= "02-24-2023"; String dtstr1= "24-02-2023"; //getting the month part of the date String substr2 = dtstr.substring(0,2); System.out.println("\nThe date is " + dtstr); System.out.println("\nThe current month is " + substr2); //getting the month part of the date String substr3 = dtstr1.substring(3,5); System.out.println("\nThe date is " + dtstr1); System.out.println("\nThe current month is " + substr3); } }
Output
The date is 02-24-2023 The current month is 02 The date is 24-02-2023 The current month is 02
Method 4: Using java.text.SimpleDateFormat
In this method, you can specify different formats as the mode for displaying dates. The month format in the date is printed in MMM form (for example, Feb) or MMMM form (for example, February). It can also be used to display month names in different locale formats and languages. For eq, the Spanish febrero means February.
Example
import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class ShowMonth33{ public static void main(String[] args) { Date dtt = new Date(); // MMM means date specification such as Feb, Mar etc SimpleDateFormat formatted_mmm; // MMMM means date specification such as February, March etc SimpleDateFormat formatted_mmmm; SimpleDateFormat formatted_datestyle; SimpleDateFormat formatted_datestyle1; formatted_mmm = new SimpleDateFormat("MMM"); System.out.println(formatted_mmm.format(dtt)); formatted_mmmm = new SimpleDateFormat("MMMM"); System.out.println(formatted_mmmm.format(dtt)); //Specifying the pattern of showing date time formatted_datestyle = new SimpleDateFormat("EEEE dd MMMM yyyy kk:mm:ss"); System.out.println(formatted_datestyle.format(dtt)); //Specifying the pattern of showing date time formatted_datestyle1 = new SimpleDateFormat("dd MMM yyyy kk:mm:ss"); System.out.println(formatted_datestyle1.format(dtt)); //setting for the Spanish language Locale spanishDT = new Locale("es","ES"); System.out.println("Now using Spanish: "); System.out.printf(spanishDT, "month: %tB\n", dtt); //setting for the French language SimpleDateFormat dt_fr = new SimpleDateFormat("dd MMM yyyy kk:mm:ss", new Locale("fr")); System.out.println("Now using French: "); System.out.println(dt_fr.format(dtt)); } }
Output
Feb February Friday 24 February 2023 19:48:31 24 Feb 2023 19:48:31 Now using Spanish: month: febrero Now using French: 24 févr. 2023 19:48:31
Method 5: Using java.util.Calendar
In this method, use the Calender object and use Calendar.MONTH to find the month. This index starts at 0, so add 1 to Calendar.MONTH to print the correct month in the date.
Example
import java.util.Calendar; public class ShowMonth44{ public static void main(String[] args) { //using Calendar instance Calendar cal = Calendar.getInstance(); //getting Time from cal System.out.println("The Current Date is: " + cal.getTime()); // Calendar Months start with 0 index therefore 1 is added for the correct result System.out.println("Current Calendar Month is : " + (cal.get(Calendar.MONTH) +1 ) ); } }
Output
The Current Date is: Fri Feb 24 19:12:06 IST 2023 Current Calendar Month is: 2
in conclusion
In this article, we explore different formats of months using Java language. Different code examples are also given along with the output for each method used.
The above is the detailed content of Java program to print months in different formats. For more information, please follow other related articles on the PHP Chinese website!

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
