Dates check in loop? - java

I have an assignment to create a Date class with given methods requests.
One of those methods give back the day of the week in integer, where 1=Sunday.....6=Friday, and 0=Saturday.
this is the method:
public int dayInWeek () {
int day, month;
int year; //2 last numbers of the year
int century; //2 first numbers of the year
if(_month==1 || _month==2) {
day= _day;
month= _month + 12;
year= (_year-1) % 100;
century= (_year-1) / 100;
}
else {
day= _day;
month= _month;
year= _year % 100;
century= _year / 100;
}
return (day + (26*(month+1))/10 + year + year/4 + century/4 - 2*century)%7;
}
Now, after receiving the day of the week, the assignment hints that there may be a date(s) where the result may be a negative.
I tried to make a main() that will loop through all days months and years from the given range years 1800-2100, but only got more and more confused and lost.
Ii'd appreciate it if someone could hint me how to make it happen, without all those existing calender/date/etc classes because it just gets messy for me like this.
Thanks.
edit: more info:
//constructors
/**
* creates a new Date object if the date is valid, otherwise creates the date 1/1/2000
* #param _day the day of the month (1-31)
* #param _month the month in the year (1-12)
* #param _year the year (1800-2100)
*/
public Date (int day, int month, int year) {
if (isValidDate (day, month, year)) {
_day=day;
_month=month;
_year=year;
}
else {
setToDefault();
}
}
/**
* copy constructor
* #param other the date to be copied
*/
public Date (Date other) {
_day= other._day;
_month= other._month;
_year= other._year;
}
//methods
private boolean isValidDate(int day, int month, int year) {
if (year<MIN_YEAR || year>MAX_YEAR) {
return false;
}
if (month<MIN_MONTH || month>MAX_MONTH) {
return false;
}
if (day<MIN_DAY) {
return false;
}
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: return day<=31;
case 4:
case 6:
case 9:
case 11: return day<=30;
default: return leap(year) ? day<=29 : day<=28; //month==2;
}
}
/**
* check if leap year
* #param y year to check
* #return true if given year is leap year
*/
private static boolean leap (int y) {
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
i hope that's enough.

You have a negative result when the year is 2100. Test with today's date (month = 3, date = 24, year = 2100) and you can see it gives a negative number.
If you take a look at Code implementation for Zeller's congruence, you can avoid the problem by changing your formula to:
return dayOfWeek= (day + (26*(month+1))/10 + year + year/4 + century/4+ 5*century)%7;

Related

Validating date from user input

I'm writing a program where I am supposed to have the user input a date from the year 0 - 4000. I'm supposed to see if the date is valid, and if it was a leap year or not. I'm having problems in my code.
I'm getting an else without error on line 57.
I also am not sure how to how to say if the date is valid or not.
IE: this date is valid, is a leap year - or is not valid is not a leap year ...etc...
I'm still a beginner so I dont want the code written for me but I would like to know how to fix it! Thank you.
import java.util.*;
public class LegalDate //file name
{
public static void main (String [] args)
{
Scanner kb = new Scanner (System.in); //new scanner
//name the variables
int month, day, year;
int daysinMonth;
boolean month1, year1, day1;
boolean validDate;
boolean leapYear;
//ask the user for input
//I asked the MM/DD/YYYY in seperate lines to help me visually with the program
System.out.println("Please enter the month, day, and year in interger form: " );
kb.nextInt();
//now I'm checking to see if the month and years are valid
if (month <1 || month >12)
{ month1 = true;}
if (year <0 || year >4000)
{year1= true;}
//I'm using a switch here instead of an if-else statement, which can also be used
switch (month) {
case 1:
case 3:
case 5: //months with 31 days
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6: //months with 30 days
case 9:
case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0)) //formula for leapyear
numDays = 29;
{
system.out.println("is a leap year");
}
else
numDays = 28;
{
system.out.println("is not a leap year");
}
break;
default:
System.out.println("Invalid month.");
break;
if (month1 == true)
if (day1 == true)
if (year1 == true)
System.out.println ("date is valid ");
else
if (month1 == false)
System.out.println ("date is invalid");
else
if (day1 == false)
System.out.println ("date is invalid");
else
if (year1 == false)
System.out.println ("date is invalid");
}}
}
On line 57, you open a new code block but nothing is able to access it. I believe you meant to type:
else{
numDays = 28;
system.out.println("is not a leap year");
}
As a small tip, you can change this:
if (month1 == true)
if (day1 == true)
if (year1 == true)
System.out.println ("date is valid ");
to this:
if (month1 && day1 && year1)
System.out.println ("date is valid ");
Since the boolean comparison operators return true or false, you can tell that the condition just needs to be boolean. Since month1, day1, and year1 are all boolean values, you dont need to compare them to anything.
What the condition means, in the event you don't know, is if month1 and day1 and year1 are all true, then print date is valid
Why don't you try Java 8 date time API
It validates date and do much more for you
Like
try {
LocalDate date =LocalDate.of(2016, 12, 31);
if(date.isLeapYear())
System.out.println("Leap year");
else
System.out.println("Not leap year");
}
catch(DateTimeException e) {
System.out.println(e.getMessage());
}
You don't appear to be placing the code between your 'if' and 'else' statements in curly brackets, which means that the statement will only apply to the next line. For example:
if (a)
b = true
c = true
else
d = true
is read as
if (a) {
b = true
}
c = true
else {
d = true
}
Hopefully, you can see how the compiler wouldn't understand this, as an 'else' statement must occur directly after its associated 'if' block.
I would suggest adding some methods to simplify your code. For example:
public static boolean isLeapYear(int year) {
return (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0));
}
Also, if you use boolean variables to store information, you can print it all neatly at the end. For example, you could instantiate a variable 'isValid' to true at the top of your code, set it to false if you calculate that the date is invalid, and use an if statement at the end to print your result.
I know you said you didn't want it written for you, but that's the easiest way to demonstrate the importance of methods. Hopefully you can see how this is more readable than your version?
import java.util.Scanner;
public class LegalDate {
static final int maxYear = 4000;
public static void main (String [] args) {
int month, day, year;
boolean leapYear, validDate = false;
Scanner kb = new Scanner (System.in);
System.out.println("Please enter the month, day, and year in interger form.");
System.out.print("Month: ");
month = kb.nextInt();
System.out.print("Day: ");
day = kb.nextInt();
System.out.print("Year: ");
year = kb.nextInt();
leapYear = isLeapYear(year);
validDate = isValidDate(month, day, year);
System.out.printf("%nThe date is %svalid and is %sa leap year.%n", validDate ? "" : "not ", leapYear ? "" : "not ");
kb.close();
}
public static int numDaysInMonth(int month, boolean isLeapYear) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if (isLeapYear) {
return 29;
} else {
return 28;
}
default:
return 0;
}
}
public static boolean isLeapYear(int year) {
return (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0));
}
public static boolean isValidDate(int month, int day, int year) {
return (month >= 1 && month <= 12) && (day >= 1 && day <= numDaysInMonth(month, isLeapYear(year))) && (year >= 0 && year <= maxYear);
}
}
If you have any questions I'll try my best to answer them!
The syntax of if-else statement on line 50 of your program is not correct.
It's a dangling else. Enclosing the body of if and else statement within braces should resolve this.
if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0))
{
numDays = 29;
system.out.println("is a leap year");
}
else
{
numDays = 28;
system.out.println("is not a leap year");
}
you can make use of IDE or give attention to compiler error message to resolve such errors.

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);

JVM does not respond when user clicks button 1/2, it just becomes stuck

I am trying to make a program that user is able to enter a date like: 28 -03 - 2014.
This and the program reads that, gives the date of tomorrow like: 29 - march - 2014.
The program must check about:
String max 10.
date of day(2 digit): 1 - 31
String: -
month (two digit): 1 - 12
String: -
year : four digits
Here is my code!
public String month()
{
int month = 0;
switch(month){
case 1 :monthString = " Janauri";
break;
case 2: monthString = "February"
.......
ublic String dateOfTomorrow(int day, int month, int year)
{
String Date = day+ "-" + month+ "- " + year;
day++;
if(day > totalDaysInMonth(month));
{// new month
day = 1;
month++;
if(month > 12)
{//new year
month= 1;
year ++;
}
}
return Date;
}
private boolean totalDaysInMonth(int day)
{
if( day >= 1 && day < 31)
{
return true;
}
else {
return false;
}
}
public void actionPerformed(ActionEvent e)
{
for ( int i = 1; i<31;);
String s = tf.getText();
if ( e.getSource() == b1)
{
l2.setText(s);
}
else if (e.getSource ()== b2)
{
l2.setText(monthString);
}
}
I think your problem is in this loop:
for ( int i = 1; i<31;);
which will never end.
Remove that empty loop or change it to:
for ( int i = 1; i<31;i++);
I don't really understand what you mean by 1/2 stack. But if you make a string of some variables
String Date = day + "-" + month + "-" + year;
and then change the variables it doesn't have any effect on the string.
So you will still get the same date back.
And a tip for better readability makes your variables camel cased. So instead of Date call it date.

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);

Whether it is correct to take 01/01/0001 date as Monday?

I am writing a program to display the Day for the given date. (E.g. Thursday for 1/1/1970.)
While attempting that I have some problems.
This is my program.
/*Concept:
The noOfDays variable will count the no of days since 01/01/0001. And this will be Day one(1). E.g
noOfDays = 365 for 01/12/0001 and noOfDays = 731 for 01/01/0003 and so on....
Since I taken Monday as 01/01/0001,the day of the specific date can be achieved by switching(noOfDays%7)
E.g. 365 % 7 = 1. So, the 365th day is monday...
*/
import java.util.Scanner;
class DayDisplayer
{
long noOfDays;
int month;
int days;
int year;
Scanner scan;
int countYear;
int countMonth;
DayDisplayer()
{
scan = new Scanner(System.in);
noOfDays = 0;
System.out.println("Enter the date please");
days = scan.nextInt();
month = scan.nextInt();
year = scan.nextInt();
System.out.println("Your Date is: "+days+"/"+month+"/"+year);
}
boolean leapYearCheck(int year)
{
if( ((year%100 == 0) && (year%400 != 0)) || (year%4 != 0) ) // when it is divisible by 100 and not by 400.
return false;
else
return true;
}
boolean isThere31Days()
{
if ( ( (countMonth >> 3) ^ (countMonth & 1) ) == 1 )
return true;
else
return false;
}
void getDaysThatInDays()
{
noOfDays += days;
}
void getDaysThatInMonth()
{
countMonth = 1;
while(countMonth<month)
{
if( countMonth == 2 )
if( leapYearCheck(year) == true)
noOfDays += 29;
else
noOfDays += 28;
else
if ( isThere31Days())
noOfDays += 31;
else
noOfDays += 30;
countMonth++;
}
}
void getDaysThatInYear()
{
countYear = 1;
while(countYear<year)
{
if( leapYearCheck(countYear)== true )
noOfDays += 366;
else
noOfDays += 365;
countYear ++;
}
}
void noOfDaysAndDayName()
{
System.out.println("The noOfDays is"+noOfDays);
System.out.println("And Your Day is :");
int day;
day = (int)(noOfDays%7);
switch(day)
{
case 0:
System.out.println("Sunday");
break;
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
}
}
}// end of MonthToDate class
public class Main
{
public static void main(String args[])
{
DayDisplayer dd= new DayDisplayer();
dd.getDaysThatInYear();
dd.getDaysThatInMonth();
dd.getDaysThatInDays();
dd.noOfDaysAndDayName();
}
}
In this code ,when I take 01/01/0001 as Monday and calculated the other days. And I am getting correct answers.
But In www.timeanddate.com website they took 01/01/0001 as Saturday.
But still for the other recent dates (say 17/7/2011) they are giving the correct answer (as Sunday).
I could guess these lags are due to the migration of Julier system to Gregorian system.
But I have a doubt whether my approach of calculating the Days from 0001 year is correct or not?
Also I have a doubt about whether to take 01/01/0001 date is Monday or Saturday.
(And If I took Saturday as my first day, I am getting wrong answers.)
someone please explain.
Thanks in advance.
One problem could be highlighted by an off-by-one error your opening comment:
The noOfDays variable will count the no of days since 01/01/0001. E.g
noOfDays = 365 for 01/12/0001 and noOfDays = 731 for 01/01/0003 and so on.
That says that 0001-01-01 will be day 0 (0 days since the reference date), which in turn means that 0001-12-31 on your proleptic Gregorian calendar will be 364, not 365.
You can adjust this in either of two ways:
Define that 0001-01-01 will be day 1 (whereupon the rest of the quoted fragment of comment is correct).
Change the comment values to 364 and 730.
Another problem with reverse engineering dates back that far is understanding the 'proleptic' Gregorian calendar. The term strictly means 'the representation of a thing as existing before it actually does or did so', and applies forward, but the term is also used in calendrical calculations to refer to applying the present rules backwards in time. The issue at hand is that the Gregorian calendar with its rules for leap years (divisible by 400, or divisible by 4 but not divisible by 100) did not exist in year 1. And the question is: did the web sites you referred to compensate for the switch between the Julian calendar and the Gregorian? (Underlying that are a lot of complications; the calendar was exceptionally volatile, even in the Roman Empire, between about 55 BCE and 200 CE.)
An excellent book for considering matters of date is Calendrical Calculations.
You could always compare to what Java itself gives you:
import java.util.Scanner;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.FieldPosition;
public class Test {
public static void main (String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the date please");
int days = scan.nextInt();
int month = scan.nextInt();
int year = scan.nextInt();
SimpleDateFormat sdf = new SimpleDateFormat("E dd-MM-yyyy G");
StringBuffer buf = new StringBuffer();
Calendar cal = new GregorianCalendar();
cal.set(year, month-1, days);
sdf.format(cal.getTime(), buf, new FieldPosition(0));
System.out.println(buf.toString());
}
}
So we get:
> java Test
Enter the date please
1
1
0001
Sat 01-01-0001 AD
which seems to agree with the website...

Categories