How to use switch-statement correctly? - java

I need to write a Java program (class NextDay) that calculates and prints the date of the next day by entering the day, month, and year.
Sample call and output:
Actual Date 12.12.2004
The next day is the 13.12.2004.
The input should also be checked for correctness! If an erroneous date constellation (e.g., 32 12 2007) has been entered, the exception InvalidDateArgumentsException is to be thrown. Define this class in a suitable form as a subclass of the class java.lang.Exception.
I started to creating it but the problem is; i cant tell that < or > in switch statements.What should i do? Here are my classes:
public class Date {
private int day;
private int month;
private int year;
public Date(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public Date getNextDay() throws Exception {
if (isLeapYear() == true) {
switch (month) {
case 1:
day = 31;
break;
case 2:
day = 29;
break;
case 3:
day = 31;
break;
case 4:
day = 30;
break;
case 5:
day = 31;
break;
case 6:
day = 30;
break;
case 7:
day = 31;
break;
case 8:
day = 31;
break;
case 9:
day = 30;
break;
case 10:
day = 31;
break;
case 11:
day = 30;
break;
case 12:
day = 31;
break;
}
}
return new Date(day + 1, month, year);
}
public int getDay() {
return day;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}
public boolean isLeapYear() {
if (year % 4 == 0 && year % 100 != 0 && year % 400 == 0) {
return true;
}
return false;
}
public String toString() {
return this.day + "." + this.month + "." + this.year;
}
}
...
public class NextDay {
public static void main(String args[]) throws Exception {
Date dateObj = new Date(20, 5, 2016);
System.out.println("Old Date: " + dateObj.getDay() + "." + dateObj.getMonth() + "." + dateObj.getYear() + ".");
System.out.println("The next day is " + dateObj.getNextDay().toString() + ".");
}
}

You are saying that you want an "or" statement inside switch, right? If you write case labels line by line you get "or statement", like this:
switch(variable){
case 1:
case 2:
case 3: {
//.. when variable equals to 1 or 2 or 3
}
}
So that, you can write your getMaxDaysInMonth method like this:
int getMaxDaysInMonth()
{
int daysInMonth = 0;
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
daysInMonth = 31;
break;
case 2:
if(isLeapYear())
{
daysInMonth = 29;
}
else
{
daysInMonth = 28;
}
break;
case 4:
case 6:
case 9:
case 11:
daysInMonth = 30;
}
return daysInMonth;
}
Also, you are checking for the leap year incorrectly. Here's the correct way:
boolean isLeapYear(){
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
And here's how you increment a day:
void incrementDate(){
if((day + 1) > getMaxDaysInMonth())
{
day = 1;
if (month == 12)
{
month = 1;
year++;
}else{
month++;
}
} else {
day++;
}
}

EDIT since we can't just use standard classes
If you have to use switch case, you should use it to set max day in current month and then check, if your current day more than this max day:
int maxDay;
switch (month) {
case 1: maxDay = 31; break;
case 2: maxDay = isLeapYear() ? 29 : 28; break;
case 3: maxDay = 31; break;
// ... other months ...
case 12: maxDay = 31; break;
default: throw new InvalidDateArgumentsException();
}
if (isLeapYear()) {
maxDay = 29;
}
if (day > maxDay) {
throw new InvalidDateArgumentsException();
}

Related

illegal start of expression [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have been searching all around the web to find a solution but no
luck was found. So i went to stack overflow to see some solutions but still no luck so i am posting my code to share and help me fix this. Thank you Guys!
public class MyDate {
private int month;
private int day;
private int year;
private String MoInTxt;
private int dayz;
public MyDate(){
this(1, 1, 1990);
}
public MyDate(int d, int m, int y){
setDay(d);
setMonth(m);
setYear(y);
}
// Setter
public String MonthToTxt() {
int mo = month;
switch (mo) {
case 1: MoInTxt = "January";
break;
case 2: MoInTxt = "February";
break;
case 3: MoInTxt = "March";
break;
case 4: MoInTxt = "April";
break;
case 5: MoInTxt = "May";
break;
case 6: MoInTxt = "June";
break;
case 7: MoInTxt = "July";
break;
case 8: MoInTxt = "August";
break;
case 9: MoInTxt = "September";
break;
case 10: MoInTxt = "October";
break;
case 11: MoInTxt = "November";
break;
case 12: MoInTxt = "December";
break;
default: MoInTxt = "Invalid month";
break;
}
}
public void setMonth(int m) {
if(m>=1 && m <=12) {
month = m;
if(m ==2 && LeapChecker(year) == true) {
month = 29;
}else{
month = 28;
}
}else {
month = 1;
}
}
public void setDay(int d) {
if(day>0) {
day = d;
}else{
day = 1;
}
public void setYear(int yr) {
if (yr >=1900){
year = yr;
} else {
year = 1900;
}
}
// Getter
public int getMonth() {
return month;
}
public int getDay() {
return day;
}
public int getYear() {
return year ;
}
//==============================//
public String getCompleteDate(){
return String.format ("%s %02d, %d", MoInTxt, day, year);
}
//==============================//
public void addDays(int dey) {
int addedDey = dey + day;
int ToAddMos=0;
if(addedDey <=28) {
setDay(addedDey);
} else {
while(addedDey>28){
if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month == 12){
if(addedDey>31){
addedDey=addedDey-31;
setDay(addedDey);
ToAddMos++;
}else{
setDay(addedDey);
break;
}
}else if(month ==2) {
if(LeapChecker(year) == true){
if(addedDey >29) {
addedDey = addedDey - 29;
ToAddMos++;
}else {
setDay(addedDey);
break;
}
}else if(LeapChecker(year) == false) {
if(a>28){
addedDey = addedDey - 28;
ToAddMos++;
}else{
setDay(AddedDey);
break;
}
}
}else if(month == 4 || month == 6 || month == 9 || month == 11){
if(addedDey>30){
addedDey-=30;
ToAddMos++;
} else {
setDay(addedDey);
break;
}
}
}
}
}
public void addMonths(int mon) {
int addedMon = mon + month;
setMonth(addedMon);
}
public void addYears(int yir) {
int addedYir = year + yir;
setYear(addedYir);
}
/* Method Name: Leap Checker
* This Method checks if that year is a leap year or not
* 1. It checks if the year is divisible by 400
* 2. It checks if the year is divisible by 4
* 3. It checks if the year is not divisible by 100
*/
public boolean LeapChecker(int year){
year = year;
boolean isLeap =true;
if((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
isLeap = true;
} else {
isLeap = false;
}
return isLeap;
}
}
}
The problem is a missing closing curly brace at the end of the setDay() method:
public void setDay(int d) {
if(day>0) {
day = d;
}else{
day = 1;
} // <------------------ this one
}
public void setDay(int d) {
if(day>0) {
day = d;
}else{
day = 1;
}//Missing closing the else block
}

Unable to print correct Calendar on Java

Can anyone help me find what is wrong with my code? I cannot figure out how to display the correct start day of the month (Note that the January 1, 1900 was a Monday) or to display the correct number of days in the month of February if the year is a leap year.
public class Calendar {
/**
*
*
* #param s
* #return
*/
public static int getMonthNumber(String s){
if (s.equalsIgnoreCase("jan"))
return 1;
if (s.equalsIgnoreCase("feb"))
return 2;
if (s.equalsIgnoreCase("mar"))
return 3;
if (s.equalsIgnoreCase("apr"))
return 4;
if (s.equalsIgnoreCase("may"))
return 5;
if (s.equalsIgnoreCase("jun"))
return 6;
if (s.equalsIgnoreCase("jul"))
return 7;
if (s.equalsIgnoreCase("aug"))
return 8;
if (s.equalsIgnoreCase("sep"))
return 9;
if (s.equalsIgnoreCase("oct"))
return 10;
if (s.equalsIgnoreCase("nov"))
return 11;
if (s.equalsIgnoreCase("dec"))
return 12;
else
System.out.println("Not valid month!");
return 0;
}
public static boolean isLeapYear(int year){
int month = 0;
int s = getDaysIn(month, year);
return year%4==0 && (year % 100 != 0) || (year % 400 == 0);
}
public static int getDaysIn (int month, int year){
switch (month) {
case 1: return 31;
case 2: if(isLeapYear(month)) return 29;
else return 28;
case 3: return 31;
case 4: return 30;
case 5: return 31;
case 6: return 30;
case 7: return 31;
case 8: return 31;
case 9: return 30;
case 10: return 31;
case 11: return 30;
case 12: return 31;
default: return -1;
}
}
public static String getMonthName (int month){
switch (month) {
case 1: return "January";
case 2: return "February";
case 3: return "March";
case 4: return "April";
case 5: return "May";
case 6: return "June";
case 7: return "July";
case 8: return "August";
case 9: return "September";
case 10: return "October";
case 11: return "November";
case 12: return "December";
default: return "Invalid month.";
}
}
public static int getStartDay (int month, int year){
int days = 0;
for (int i = 1900; i<year; i++){
days = days + 365;
if (isLeapYear(i))
days = days + 1;}
for (int i=1; i<month; i++)
days = days + getDaysIn(month, year);
int startday = (days + 1)%7+1;
return startday;
}
public static void displayCalendar(int month, int year){
String monthname=getMonthName(month);
int startDay= getStartDay(month, year);
int monthDays = getDaysIn(month, year);
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
int weekDay = startDay-1;
for (int i=1; i<=startDay; i=i+1)
System.out.print(" ");
for ( int x=1; x<=monthDays; x++){
weekDay = weekDay +1;
if (weekDay>7){
System.out.println();
weekDay = 1;}
System.out.format(" %3d",x);
}
if (weekDay > 7){
System.out.println();
}
}
public static void main(String[] args){
Scanner c = new Scanner (System.in);
System.out.print("Give the first three letters of a month and enter the year: ");
String month,year;
month=c.next();
year=c.next();
int yearno =Integer.parseInt(year);
int monthno = getMonthNumber(month);
displayCalendar(monthno, yearno);
}
}
Suppose that you can use the java.util.Calendar, I would code something like this:
import java.util.Calendar;
import java.util.Scanner;
public class CalendarPrinter {
private Calendar c = null;
CalendarPrinter(int month, int year ){
c = Calendar.getInstance();
c.clear();
c.set(Calendar.MONTH, month);
c.set(Calendar.YEAR, year);
}
public String showCalendar(){
StringBuffer calendarTxt = new StringBuffer("Sun\tMon\tTue\tWed\tThu\tFri\tSat\n");
int daysInAMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDayOfWeek = c.getFirstDayOfWeek();
int i = 1;
do {
if (i < c.get(Calendar.DAY_OF_WEEK)){
calendarTxt.append("\t");
daysInAMonth++;
} else {
calendarTxt.append(firstDayOfWeek+"\t");
firstDayOfWeek++;
}
if (i%7 == 0 && i != 1){
calendarTxt.append("\n");
}
i++;
} while (i <= daysInAMonth);
return calendarTxt.toString();
}
public static int getMonthNumber(String s){
if (s.equalsIgnoreCase("jan"))
return 0;
if (s.equalsIgnoreCase("feb"))
return 1;
if (s.equalsIgnoreCase("mar"))
return 2;
if (s.equalsIgnoreCase("apr"))
return 3;
if (s.equalsIgnoreCase("may"))
return 4;
if (s.equalsIgnoreCase("jun"))
return 5;
if (s.equalsIgnoreCase("jul"))
return 6;
if (s.equalsIgnoreCase("aug"))
return 7;
if (s.equalsIgnoreCase("sep"))
return 8;
if (s.equalsIgnoreCase("oct"))
return 9;
if (s.equalsIgnoreCase("nov"))
return 10;
if (s.equalsIgnoreCase("dec"))
return 11;
else
System.out.println("Not valid month!");
return 0;
}
public static void main(String[] args){
Scanner input = new Scanner (System.in);
System.out.print("Give the first three letters of a month and enter the year: ");
String month;
int year;
month=input.next();
year=input.nextInt();
CalendarPrinter c = new CalendarPrinter(getMonthNumber(month), year);
System.out.println(c.showCalendar());
}
}
Here is an example just for days of week based on Zeller's congruence.
Sample code:
class Ideone
{
public static void main (String[] args) {
System.out.println(days()[dow(8,10,2015)]);
}
public static String[] days() {
return new String[] {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
}
public static int dow(int d, int m, int y) {
if (m < 3) {
m += 12;
y--;
}
return (d + (int)((m+1)*2.6) + y + (int)(y/4) + 6*(int)(y/100) + (int)(y/400) + 6) % 7;
}
}
Running code here
Code reference here

printing out the day of the week in Java

Im trying to get my program to print out the day of any given date using functions that I have to write and declare, although for the early dates of the month the program doesnt seem to print the write day. The equation in the dayOfTheWeek function, w, was given to us to calculate for the day, although for the 'floor' code to be used i had to create another 'private static' function for reasons im not quite sure of, any reason as to why would be great as well as any reason for why my program isnt returning the right day for certain dates.
here's my code, any help would be greatly appreciated :)
import java.util.Scanner;
import javax.swing.JOptionPane;
public class DayOfTheWeek {
public static final int SEPTEMBER_APRIL_JUNE_NOVEMBER_DAYS = 30;
public static final int REST_OF_YEAR_DAYS = 31;
public static final int LEAP_YEAR_FEB = 29;
public static final int NORMAL_FEB = 28;
public static final int MONTHS = 12;
public static void main(String[] args) {
try
{
String input = JOptionPane.showInputDialog("Enter date (day/month/year):");
Scanner scanner = new Scanner( input );
scanner.useDelimiter("/");
int day = scanner.nextInt();
int month = scanner.nextInt();
int year = scanner.nextInt();
scanner.close();
String numberEnding = numberEnding (day);
String dayEnding = day + numberEnding;
String monthName = monthName (month);
String dayName = dayOfTheWeek (day, month, year);
if (validDate(day, month, year))
{
JOptionPane.showMessageDialog(null, dayName + " " + dayEnding + " " + monthName
+ " " + year + " is a valid date.");
}
else
{
JOptionPane.showMessageDialog(null, "" + dayEnding + " " + monthName
+ " " + year + " is not a valid date.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
catch (NullPointerException exception)
{
}
catch (java.util.NoSuchElementException exception)
{
JOptionPane.showMessageDialog(null, "No number entered. \nPlease restart and try again.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
public static boolean validDate( int day, int month, int year ) {
return ((year >= 0) && (month >= 1) && (month <= MONTHS) &&
(day >= 1) && (day <= daysInMonth( month, year )));
}
public static int daysInMonth( int month, int year ) {
int monthDays;
switch (month)
{
case 2:
monthDays = isLeapYear(year) ? LEAP_YEAR_FEB : NORMAL_FEB;
break;
case 4:
case 6:
case 9:
case 11:
monthDays = SEPTEMBER_APRIL_JUNE_NOVEMBER_DAYS;
break;
default:
monthDays = REST_OF_YEAR_DAYS;
}
return monthDays;
}
public static boolean isLeapYear( int year ) {
return (((year%4 == 0) && (year%100 != 0)) || (year%400 == 0));
}
public static String numberEnding( int day ) {
String dayEnding = "";
int remainder = day%10;
if (day >= 10 && day <= 20)
{
dayEnding = "th";
}
else
{
switch (remainder)
{
case 1:
dayEnding = "st";
break;
case 2:
dayEnding = "nd";
break;
case 3:
dayEnding = "rd";
break;
default:
dayEnding = "th";
break;
}
}
return dayEnding;
}
public static String monthName( int month ) {
String monthName = "";
switch (month)
{
case 1:
monthName = "January";
break;
case 2:
monthName = "February";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
break;
default:
}
return monthName;
}
public static String dayOfTheWeek (int day, int month, int year){
String dayName = "";
int Y;
if (month == 1 || month == 2)
{
Y = (year-1);
}
else
{
Y = (year);
}
int y = Y%100;
int c = Y/100;
int w = (day + floor(2.6 * (((month+9) % 12)+ 1) -0.2)
+ y + floor(y/4) + floor(c/4) - (2*c));
w = (w%7);
if (w < 0)
{
w += 7;
}
switch (w)
{
case 0:
dayName = "Sunday";
break;
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
}
return dayName;
}
private static int floor(double d) {
return 0;
}
}
I believe you need to use the Math.floor() method. Simply call this in place of your floor method:
(day + Math.floor(2.6 * (((month+9) % 12)+ 1) -0.2)
+ y + Math.floor(y/4) + Math.floor(c/4) - (2*c));
You can also cast the equation directly using (int):
int w = (int) (day + 2.6 * ((month+9) % 12 + 1) - 0.2 + y + (y/4) + (c/4) - (2*c));
However, in your case I think that the values will be rounded improperly using casting, so you should probably use the floor method.
If you'd like some additional information on the differences between floor and casting here's a stackoverflow question that addresses it: Cast to int vs floor
I would use the Joda-Time library.
import org.joda.time.DateTime
final DateTime date = new DateTime();
final int dayOfWeek = date.getDayOfWeek();
See the Joda-Time User Guide for more info and examples..

Get Number of Days of one month and year JAVA [duplicate]

How to know how many days has particular month of particular year?
String date = "2010-01-19";
String[] ymd = date.split("-");
int year = Integer.parseInt(ymd[0]);
int month = Integer.parseInt(ymd[1]);
int day = Integer.parseInt(ymd[2]);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
int daysQty = calendar.getDaysNumber(); // Something like this
Java 8 and later
#Warren M. Nocos.
If you are trying to use Java 8's new Date and Time API, you can use java.time.YearMonth class. See Oracle Tutorial.
// Get the number of days in that month
YearMonth yearMonthObject = YearMonth.of(1999, 2);
int daysInMonth = yearMonthObject.lengthOfMonth(); //28
Test: try a month in a leap year:
yearMonthObject = YearMonth.of(2000, 2);
daysInMonth = yearMonthObject.lengthOfMonth(); //29
Java 7 and earlier
Create a calendar, set year and month and use getActualMaximum
int iYear = 1999;
int iMonth = Calendar.FEBRUARY; // 1 (months begin with 0)
int iDay = 1;
// Create a calendar object and set year and month
Calendar mycal = new GregorianCalendar(iYear, iMonth, iDay);
// Get the number of days in that month
int daysInMonth = mycal.getActualMaximum(Calendar.DAY_OF_MONTH); // 28
Test: try a month in a leap year:
mycal = new GregorianCalendar(2000, Calendar.FEBRUARY, 1);
daysInMonth= mycal.getActualMaximum(Calendar.DAY_OF_MONTH); // 29
Code for java.util.Calendar
If you have to use java.util.Calendar, I suspect you want:
int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
Code for Joda Time
Personally, however, I'd suggest using Joda Time instead of java.util.{Calendar, Date} to start with, in which case you could use:
int days = chronology.dayOfMonth().getMaximumValue(date);
Note that rather than parsing the string values individually, it would be better to get whichever date/time API you're using to parse it. In java.util.* you might use SimpleDateFormat; in Joda Time you'd use a DateTimeFormatter.
You can use Calendar.getActualMaximum method:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
int numDays = calendar.getActualMaximum(Calendar.DATE);
java.time.LocalDate
From Java 1.8, you can use the method lengthOfMonth on java.time.LocalDate:
LocalDate date = LocalDate.of(2010, 1, 19);
int days = date.lengthOfMonth();
This is the mathematical way:
For year (e.g. 2012), month (1 to 12):
int daysInMonth = month !== 2 ?
31 - (((month - 1) % 7) % 2) :
28 + (year % 4 == 0 ? 1 : 0) - (year % 100 == 0 ? 1 : 0) + (year % 400 == 0 ? 1 : 0)
if (month == 4 || month == 6 || month == 9 || month == 11) {
daysInMonth = 30;
} else if (month == 2) {
daysInMonth = (leapYear) ? 29 : 28;
else {
daysInMonth = 31;
}
I would go for a solution like this:
int monthNr = getMonth();
final Month monthEnum = Month.of(monthNr);
int daysInMonth;
if (monthNr == 2) {
int year = getYear();
final boolean leapYear = IsoChronology.INSTANCE.isLeapYear(year);
daysInMonth = monthEnum.length(leapYear);
} else {
daysInMonth = monthEnum.maxLength();
}
If the month isn't February (92% of the cases), it depends on the month only and it is more efficient not to involve the year. This way, you don't have to call logic to know whether it is a leap year and you don't need to get the year in 92% of the cases.
And it is still clean and very readable code.
Simple as that,no need to import anything
public static int getMonthDays(int month, int year) {
int daysInMonth ;
if (month == 4 || month == 6 || month == 9 || month == 11) {
daysInMonth = 30;
}
else {
if (month == 2) {
daysInMonth = (year % 4 == 0) ? 29 : 28;
} else {
daysInMonth = 31;
}
}
return daysInMonth;
}
In Java8 you can use get ValueRange from a field of a date.
LocalDateTime dateTime = LocalDateTime.now();
ChronoField chronoField = ChronoField.MONTH_OF_YEAR;
long max = dateTime.range(chronoField).getMaximum();
This allows you to parameterize on the field.
Lets make it as simple if you don't want to hardcode the value of year and month and you want to take the value from current date and time:
Date d = new Date();
String myDate = new SimpleDateFormat("dd/MM/yyyy").format(d);
int iDayFromDate = Integer.parseInt(myDate.substring(0, 2));
int iMonthFromDate = Integer.parseInt(myDate.substring(3, 5));
int iYearfromDate = Integer.parseInt(myDate.substring(6, 10));
YearMonth CurrentYear = YearMonth.of(iYearfromDate, iMonthFromDate);
int lengthOfCurrentMonth = CurrentYear.lengthOfMonth();
System.out.println("Total number of days in current month is " + lengthOfCurrentMonth );
// 1 means Sunday ,2 means Monday .... 7 means Saturday
//month starts with 0 (January)
MonthDisplayHelper monthDisplayHelper = new MonthDisplayHelper(2019,4);
int numbeOfDaysInMonth = monthDisplayHelper.getNumberOfDaysInMonth();
Following method will provide you the no of days in a particular month
public static int getNoOfDaysInAMonth(String date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return (cal.getActualMaximum(Calendar.DATE));
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/*
* 44. Return the number of days in a month
* , where month and year are given as input.
*/
public class ex44 {
public static void dateReturn(int m,int y)
{
int m1=m;
int y1=y;
String str=" "+ m1+"-"+y1;
System.out.println(str);
SimpleDateFormat sd=new SimpleDateFormat("MM-yyyy");
try {
Date d=sd.parse(str);
System.out.println(d);
Calendar c=Calendar.getInstance();
c.setTime(d);
System.out.println(c.getActualMaximum(Calendar.DAY_OF_MONTH));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
dateReturn(2,2012);
}
}
public class Main {
private static LocalDate local=LocalDate.now();
public static void main(String[] args) {
int month=local.lengthOfMonth();
System.out.println(month);
}
}
The use of outdated Calendar API should be avoided.
In Java8 or higher version, this can be done with YearMonth.
Example code:
int year = 2011;
int month = 2;
YearMonth yearMonth = YearMonth.of(year, month);
int lengthOfMonth = yearMonth.lengthOfMonth();
System.out.println(lengthOfMonth);
You can use Calendar.getActualMaximum method:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month-1);
int numDays = calendar.getActualMaximum(Calendar.DATE);
And month-1 is Because of month takes its original number of month while in method takes argument as below in Calendar.class
public int getActualMaximum(int field) {
throw new RuntimeException("Stub!");
}
And the (int field) is like as below.
public static final int JANUARY = 0;
public static final int NOVEMBER = 10;
public static final int DECEMBER = 11;
An optimal and performant variance:
public static int daysInMonth(int month, int year) {
if (month != 2) {
return 31 - (month - 1) % 7 % 2;
}
else {
if ((year & 3) == 0 && ((year % 25) != 0 || (year & 15) == 0)) { // leap year
return 29;
} else {
return 28;
}
}
}
For more details on the leap algorithm check here
Number of days in particular year - Java 8+ solution
Year.now().length()
An alternative solution is to use a Calendar object. Get the current date and set the day so it is the first of the month. Then add one month and take away one day to get the last day of the current month. Finally fetch the day to get the number of days in the month.
Calendar today = getInstance(TimeZone.getTimeZone("UTC"));
Calendar currMonthLastDay = getInstance(TimeZone.getTimeZone("UTC"));
currMonthLastDay.clear();
currMonthLastDay.set(YEAR, today.get(YEAR));
currMonthLastDay.set(MONTH, today.get(MONTH));
currMonthLastDay.set(DAY_OF_MONTH, 1);
currMonthLastDay.add(MONTH, 1);
currMonthLastDay.add(DAY_OF_MONTH, -1);
Integer daysInMonth = currMonthLastDay.get(DAY_OF_MONTH);
String MonthOfName = "";
int number_Of_DaysInMonth = 0;
//year,month
numberOfMonth(2018,11); // calling this method to assign values to the variables MonthOfName and number_Of_DaysInMonth
System.out.print("Number Of Days: "+number_Of_DaysInMonth+" name of the month: "+ MonthOfName );
public void numberOfMonth(int year, int month) {
switch (month) {
case 1:
MonthOfName = "January";
number_Of_DaysInMonth = 31;
break;
case 2:
MonthOfName = "February";
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
number_Of_DaysInMonth = 29;
} else {
number_Of_DaysInMonth = 28;
}
break;
case 3:
MonthOfName = "March";
number_Of_DaysInMonth = 31;
break;
case 4:
MonthOfName = "April";
number_Of_DaysInMonth = 30;
break;
case 5:
MonthOfName = "May";
number_Of_DaysInMonth = 31;
break;
case 6:
MonthOfName = "June";
number_Of_DaysInMonth = 30;
break;
case 7:
MonthOfName = "July";
number_Of_DaysInMonth = 31;
break;
case 8:
MonthOfName = "August";
number_Of_DaysInMonth = 31;
break;
case 9:
MonthOfName = "September";
number_Of_DaysInMonth = 30;
break;
case 10:
MonthOfName = "October";
number_Of_DaysInMonth = 31;
break;
case 11:
MonthOfName = "November";
number_Of_DaysInMonth = 30;
break;
case 12:
MonthOfName = "December";
number_Of_DaysInMonth = 31;
}
}
This worked fine for me.
This is a Sample Output
import java.util.*;
public class DaysInMonth {
public static void main(String args []) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a year:");
int year = input.nextInt(); //Moved here to get input after the question is asked
System.out.print("Enter a month:");
int month = input.nextInt(); //Moved here to get input after the question is asked
int days = 0; //changed so that it just initializes the variable to zero
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
switch (month) {
case 1:
days = 31;
break;
case 2:
if (isLeapYear)
days = 29;
else
days = 28;
break;
case 3:
days = 31;
break;
case 4:
days = 30;
break;
case 5:
days = 31;
break;
case 6:
days = 30;
break;
case 7:
days = 31;
break;
case 8:
days = 31;
break;
case 9:
days = 30;
break;
case 10:
days = 31;
break;
case 11:
days = 30;
break;
case 12:
days = 31;
break;
default:
String response = "Have a Look at what you've done and try again";
System.out.println(response);
System.exit(0);
}
String response = "There are " + days + " Days in Month " + month + " of Year " + year + ".\n";
System.out.println(response); // new line to show the result to the screen.
}
} //abhinavsthakur00#gmail.com
String date = "11-02-2000";
String[] input = date.split("-");
int day = Integer.valueOf(input[0]);
int month = Integer.valueOf(input[1]);
int year = Integer.valueOf(input[2]);
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR,year);
cal.set(Calendar.MONTH,month-1);
cal.set(Calendar.DATE, day);
//since month number starts from 0 (i.e jan 0, feb 1),
//we are subtracting original month by 1
int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println(days);

Number of days in particular month of particular year?

How to know how many days has particular month of particular year?
String date = "2010-01-19";
String[] ymd = date.split("-");
int year = Integer.parseInt(ymd[0]);
int month = Integer.parseInt(ymd[1]);
int day = Integer.parseInt(ymd[2]);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
int daysQty = calendar.getDaysNumber(); // Something like this
Java 8 and later
#Warren M. Nocos.
If you are trying to use Java 8's new Date and Time API, you can use java.time.YearMonth class. See Oracle Tutorial.
// Get the number of days in that month
YearMonth yearMonthObject = YearMonth.of(1999, 2);
int daysInMonth = yearMonthObject.lengthOfMonth(); //28
Test: try a month in a leap year:
yearMonthObject = YearMonth.of(2000, 2);
daysInMonth = yearMonthObject.lengthOfMonth(); //29
Java 7 and earlier
Create a calendar, set year and month and use getActualMaximum
int iYear = 1999;
int iMonth = Calendar.FEBRUARY; // 1 (months begin with 0)
int iDay = 1;
// Create a calendar object and set year and month
Calendar mycal = new GregorianCalendar(iYear, iMonth, iDay);
// Get the number of days in that month
int daysInMonth = mycal.getActualMaximum(Calendar.DAY_OF_MONTH); // 28
Test: try a month in a leap year:
mycal = new GregorianCalendar(2000, Calendar.FEBRUARY, 1);
daysInMonth= mycal.getActualMaximum(Calendar.DAY_OF_MONTH); // 29
Code for java.util.Calendar
If you have to use java.util.Calendar, I suspect you want:
int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
Code for Joda Time
Personally, however, I'd suggest using Joda Time instead of java.util.{Calendar, Date} to start with, in which case you could use:
int days = chronology.dayOfMonth().getMaximumValue(date);
Note that rather than parsing the string values individually, it would be better to get whichever date/time API you're using to parse it. In java.util.* you might use SimpleDateFormat; in Joda Time you'd use a DateTimeFormatter.
You can use Calendar.getActualMaximum method:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
int numDays = calendar.getActualMaximum(Calendar.DATE);
java.time.LocalDate
From Java 1.8, you can use the method lengthOfMonth on java.time.LocalDate:
LocalDate date = LocalDate.of(2010, 1, 19);
int days = date.lengthOfMonth();
This is the mathematical way:
For year (e.g. 2012), month (1 to 12):
int daysInMonth = month !== 2 ?
31 - (((month - 1) % 7) % 2) :
28 + (year % 4 == 0 ? 1 : 0) - (year % 100 == 0 ? 1 : 0) + (year % 400 == 0 ? 1 : 0)
if (month == 4 || month == 6 || month == 9 || month == 11) {
daysInMonth = 30;
} else if (month == 2) {
daysInMonth = (leapYear) ? 29 : 28;
else {
daysInMonth = 31;
}
I would go for a solution like this:
int monthNr = getMonth();
final Month monthEnum = Month.of(monthNr);
int daysInMonth;
if (monthNr == 2) {
int year = getYear();
final boolean leapYear = IsoChronology.INSTANCE.isLeapYear(year);
daysInMonth = monthEnum.length(leapYear);
} else {
daysInMonth = monthEnum.maxLength();
}
If the month isn't February (92% of the cases), it depends on the month only and it is more efficient not to involve the year. This way, you don't have to call logic to know whether it is a leap year and you don't need to get the year in 92% of the cases.
And it is still clean and very readable code.
Simple as that,no need to import anything
public static int getMonthDays(int month, int year) {
int daysInMonth ;
if (month == 4 || month == 6 || month == 9 || month == 11) {
daysInMonth = 30;
}
else {
if (month == 2) {
daysInMonth = (year % 4 == 0) ? 29 : 28;
} else {
daysInMonth = 31;
}
}
return daysInMonth;
}
In Java8 you can use get ValueRange from a field of a date.
LocalDateTime dateTime = LocalDateTime.now();
ChronoField chronoField = ChronoField.MONTH_OF_YEAR;
long max = dateTime.range(chronoField).getMaximum();
This allows you to parameterize on the field.
Lets make it as simple if you don't want to hardcode the value of year and month and you want to take the value from current date and time:
Date d = new Date();
String myDate = new SimpleDateFormat("dd/MM/yyyy").format(d);
int iDayFromDate = Integer.parseInt(myDate.substring(0, 2));
int iMonthFromDate = Integer.parseInt(myDate.substring(3, 5));
int iYearfromDate = Integer.parseInt(myDate.substring(6, 10));
YearMonth CurrentYear = YearMonth.of(iYearfromDate, iMonthFromDate);
int lengthOfCurrentMonth = CurrentYear.lengthOfMonth();
System.out.println("Total number of days in current month is " + lengthOfCurrentMonth );
// 1 means Sunday ,2 means Monday .... 7 means Saturday
//month starts with 0 (January)
MonthDisplayHelper monthDisplayHelper = new MonthDisplayHelper(2019,4);
int numbeOfDaysInMonth = monthDisplayHelper.getNumberOfDaysInMonth();
Following method will provide you the no of days in a particular month
public static int getNoOfDaysInAMonth(String date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return (cal.getActualMaximum(Calendar.DATE));
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/*
* 44. Return the number of days in a month
* , where month and year are given as input.
*/
public class ex44 {
public static void dateReturn(int m,int y)
{
int m1=m;
int y1=y;
String str=" "+ m1+"-"+y1;
System.out.println(str);
SimpleDateFormat sd=new SimpleDateFormat("MM-yyyy");
try {
Date d=sd.parse(str);
System.out.println(d);
Calendar c=Calendar.getInstance();
c.setTime(d);
System.out.println(c.getActualMaximum(Calendar.DAY_OF_MONTH));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
dateReturn(2,2012);
}
}
public class Main {
private static LocalDate local=LocalDate.now();
public static void main(String[] args) {
int month=local.lengthOfMonth();
System.out.println(month);
}
}
The use of outdated Calendar API should be avoided.
In Java8 or higher version, this can be done with YearMonth.
Example code:
int year = 2011;
int month = 2;
YearMonth yearMonth = YearMonth.of(year, month);
int lengthOfMonth = yearMonth.lengthOfMonth();
System.out.println(lengthOfMonth);
You can use Calendar.getActualMaximum method:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month-1);
int numDays = calendar.getActualMaximum(Calendar.DATE);
And month-1 is Because of month takes its original number of month while in method takes argument as below in Calendar.class
public int getActualMaximum(int field) {
throw new RuntimeException("Stub!");
}
And the (int field) is like as below.
public static final int JANUARY = 0;
public static final int NOVEMBER = 10;
public static final int DECEMBER = 11;
An optimal and performant variance:
public static int daysInMonth(int month, int year) {
if (month != 2) {
return 31 - (month - 1) % 7 % 2;
}
else {
if ((year & 3) == 0 && ((year % 25) != 0 || (year & 15) == 0)) { // leap year
return 29;
} else {
return 28;
}
}
}
For more details on the leap algorithm check here
Number of days in particular year - Java 8+ solution
Year.now().length()
An alternative solution is to use a Calendar object. Get the current date and set the day so it is the first of the month. Then add one month and take away one day to get the last day of the current month. Finally fetch the day to get the number of days in the month.
Calendar today = getInstance(TimeZone.getTimeZone("UTC"));
Calendar currMonthLastDay = getInstance(TimeZone.getTimeZone("UTC"));
currMonthLastDay.clear();
currMonthLastDay.set(YEAR, today.get(YEAR));
currMonthLastDay.set(MONTH, today.get(MONTH));
currMonthLastDay.set(DAY_OF_MONTH, 1);
currMonthLastDay.add(MONTH, 1);
currMonthLastDay.add(DAY_OF_MONTH, -1);
Integer daysInMonth = currMonthLastDay.get(DAY_OF_MONTH);
String MonthOfName = "";
int number_Of_DaysInMonth = 0;
//year,month
numberOfMonth(2018,11); // calling this method to assign values to the variables MonthOfName and number_Of_DaysInMonth
System.out.print("Number Of Days: "+number_Of_DaysInMonth+" name of the month: "+ MonthOfName );
public void numberOfMonth(int year, int month) {
switch (month) {
case 1:
MonthOfName = "January";
number_Of_DaysInMonth = 31;
break;
case 2:
MonthOfName = "February";
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
number_Of_DaysInMonth = 29;
} else {
number_Of_DaysInMonth = 28;
}
break;
case 3:
MonthOfName = "March";
number_Of_DaysInMonth = 31;
break;
case 4:
MonthOfName = "April";
number_Of_DaysInMonth = 30;
break;
case 5:
MonthOfName = "May";
number_Of_DaysInMonth = 31;
break;
case 6:
MonthOfName = "June";
number_Of_DaysInMonth = 30;
break;
case 7:
MonthOfName = "July";
number_Of_DaysInMonth = 31;
break;
case 8:
MonthOfName = "August";
number_Of_DaysInMonth = 31;
break;
case 9:
MonthOfName = "September";
number_Of_DaysInMonth = 30;
break;
case 10:
MonthOfName = "October";
number_Of_DaysInMonth = 31;
break;
case 11:
MonthOfName = "November";
number_Of_DaysInMonth = 30;
break;
case 12:
MonthOfName = "December";
number_Of_DaysInMonth = 31;
}
}
This worked fine for me.
This is a Sample Output
import java.util.*;
public class DaysInMonth {
public static void main(String args []) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a year:");
int year = input.nextInt(); //Moved here to get input after the question is asked
System.out.print("Enter a month:");
int month = input.nextInt(); //Moved here to get input after the question is asked
int days = 0; //changed so that it just initializes the variable to zero
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
switch (month) {
case 1:
days = 31;
break;
case 2:
if (isLeapYear)
days = 29;
else
days = 28;
break;
case 3:
days = 31;
break;
case 4:
days = 30;
break;
case 5:
days = 31;
break;
case 6:
days = 30;
break;
case 7:
days = 31;
break;
case 8:
days = 31;
break;
case 9:
days = 30;
break;
case 10:
days = 31;
break;
case 11:
days = 30;
break;
case 12:
days = 31;
break;
default:
String response = "Have a Look at what you've done and try again";
System.out.println(response);
System.exit(0);
}
String response = "There are " + days + " Days in Month " + month + " of Year " + year + ".\n";
System.out.println(response); // new line to show the result to the screen.
}
} //abhinavsthakur00#gmail.com
String date = "11-02-2000";
String[] input = date.split("-");
int day = Integer.valueOf(input[0]);
int month = Integer.valueOf(input[1]);
int year = Integer.valueOf(input[2]);
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR,year);
cal.set(Calendar.MONTH,month-1);
cal.set(Calendar.DATE, day);
//since month number starts from 0 (i.e jan 0, feb 1),
//we are subtracting original month by 1
int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println(days);

Categories