Write a program to print month of the year in Java.
import java.util.*;
import java.time.*;
import java.time.temporal.TemporalAdjusters;
/**
*
* finding current month using Calendar class and LocalDate
*/
public class CurrentMonthInJava{
public static void main(String[] args) {
String[] month = {"January", "February", "March", "April", "May", "June", "July", "August","September", "October", "November", "December" };
Calendar c=Calendar.getInstance();
System.out.println(c);
int mon=c.get(Calendar.MONTH)+1;
System.out.println("The current month of year is "+month[mon-1]);
System.out.println("The previous month of year is "+month[mon-2]);
System.out.println("The next month of year is "+month[mon]);
// month,year
LocalDate today = LocalDate.now();
LocalDate currentDate = LocalDate.parse(""+today);
// Get day from date
int day = currentDate.getDayOfMonth();
// method 1: Get month from date using currentDate
Month m = currentDate.getMonth();
// method 2: Get month from date using today
Month m1=today.getMonth();
// Get year from date
int year = currentDate.getYear();
// Print the day, month, and year
System.out.println("Current Day: " + day);
System.out.println("Current Month: " + m);
System.out.println("Current Year: " + year);
System.out.println(m1);
// Printing remaining number of months
System.out.println("Today is: "+today);
LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear());
Period period = today.until(lastDayOfYear);
System.out.println("Months remaining in the year: "+period.getMonths());
}
}
Output:
java.util.GregorianCalendar[time=1653191579706,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=4,WEEK_OF_YEAR=22,WEEK_OF_MONTH=4,DAY_OF_MONTH=22,DAY_OF_YEAR=142,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=4,AM_PM=0,HOUR=9,HOUR_OF_DAY=9,MINUTE=22,SECOND=59,MILLISECOND=706,ZONE_OFFSET=19800000,DST_OFFSET=0]
The current month of year is May
The previous month of year is April
The next month of year is June
Current Day: 22
Current Month: MAY
Current Year: 2022
MAY
Today is: 2022-05-22
Months remaining in the year: 7
No comments:
Post a Comment