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

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

Related

Dates check in loop?

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;

Java Gregorian calendar outputting wrong date

im working on a Gregorian calendar project where i have to print 100 days from today and day of week of my birthday. The program displays a day, however its the wrong day. could you guys help me with the problem? thanks!
import java.util.GregorianCalendar;
public class Gregorian {
public static void main(String[] args)
{
Day today = new Day();
System.out.print("Today: ");
System.out.println(today.toString());
GregorianCalendar Date = new GregorianCalendar();
Date.add(GregorianCalendar.DAY_OF_MONTH, 100);
CalendarUtils utils = new CalendarUtils();
String day = utils.getWeekday(Date.get(GregorianCalendar.DAY_OF_WEEK));
int year=Date.get(GregorianCalendar.YEAR);
int month=Date.get(GregorianCalendar.MONTH);
int dayof=Date.get(GregorianCalendar.DAY_OF_MONTH);
System.out.println("100 days from today: " + year + "/" + month + "/" + dayof + " which is a: " + day);
GregorianCalendar Birthday = new GregorianCalendar(2012,1,1);
String Bday = utils.getWeekday(Birthday.get(GregorianCalendar.DAY_OF_WEEK ));
System.out.println("Weekday of my Birthday: " + Bday );
Birthday.add(GregorianCalendar.DAY_OF_MONTH, 10000);
int Byear=Birthday.get(GregorianCalendar.YEAR);
int Bmonth=Birthday.get(GregorianCalendar.MONTH);
int Bdayof=Birthday.get(GregorianCalendar.DAY_OF_MONTH);
System.out.println("10000 days from my Birthday: " + Byear + "/" + Bmonth + "/" + Bdayof);
Here is the CalendarUtils
import java.util.GregorianCalendar;
public class CalendarUtils
{
/**
Returns the String for GregorianCalendar DAY_OF_WEEK
*/
public String getWeekday(int day_of_week)
{
String day = "";
if (day_of_week == GregorianCalendar.SUNDAY)
{
day = "Sunday";
}
else if (day_of_week == GregorianCalendar.MONDAY)
{
day = "Monday";
}
else if (day_of_week == GregorianCalendar.TUESDAY)
{
day = "Tuesday";
}
else if (day_of_week == GregorianCalendar.WEDNESDAY)
{
day = "Wednesday";
}
else if (day_of_week == GregorianCalendar.THURSDAY)
{
day = "Thursday";
}
else if (day_of_week == GregorianCalendar.FRIDAY)
{
day = "Friday";
}
else if (day_of_week == GregorianCalendar.SATURDAY)
{
day = "Saturday";
}
return day;
}
/**
Returns the string of GregorianCalendar MONTH
*/
public String getMonth(int month)
{
String monthStr = "";
if (month == GregorianCalendar.JANUARY)
{
monthStr = "January";
}
else if (month == GregorianCalendar.FEBRUARY)
{
monthStr = "February";
}
else if (month == GregorianCalendar.MARCH)
{
monthStr = "March";
}
else if (month == GregorianCalendar.APRIL)
{
monthStr = "April";
}
else if (month == GregorianCalendar.MAY)
{
monthStr = "May";
}
else if (month == GregorianCalendar.JUNE)
{
monthStr = "June";
}
else if (month == GregorianCalendar.JULY)
{
monthStr = "July";
}
else if (month == GregorianCalendar.AUGUST)
{
monthStr = "August";
}
else if (month == GregorianCalendar.SEPTEMBER)
{
monthStr = "September";
}
else if (month == GregorianCalendar.OCTOBER)
{
monthStr = "October";
}
else if (month == GregorianCalendar.NOVEMBER)
{
monthStr = "November";
}
else if (month == GregorianCalendar.DECEMBER)
{
monthStr = "December";
}
return monthStr;
}
}
tl;dr
LocalDate.now() // Determine current date (no time-of-day) for the JVM’s current default time zone.
.plusDays( 100 ) // Add days.
.getDayOfWeek() // Get `DayOfWeek` enum object.
.getDisplayName( FormatStyle.FULL , Locale.ITALY ) // Generate a string of the name of this day-of-week automatically localized with a certain length/abbreviation.
Details
The troublesome Calendar class is now legacy, supplanted by the java.time classes.
You want to add a hundred days after today.
LocalDate today = LocalDate.now();
LocalDate hundred = today.plusDays( 100 );
You want the day-of-week of your birthday this year.
MonthDay birthday = MonthDay.of( Month.JANUARY , 23 );
LocalDate birthdayThisYear = birthday.atYear( today.getYear() );
DayOfWeek dow = birthdayThisYear.getDayOfWeek();
You want the name of month and name of day-of-week. Let java.time automatically localize for you.
Locale locale = Locale.CANADA_FRENCH ; // Or Locale.US, etc.
String m = today.getMonth().getDisplayName( TextStyle.FULL , locale );
String d = dow.getDisplayName( TextStyle.FULL , locale );
I suppose you want to enter the 1st of January 2012 as the birthday? The the correct line would be:
GregorianCalendar Birthday = new GregorianCalendar(2012, 0, 1);
or better:
GregorianCalendar Birthday = new GregorianCalendar(2012, Calendar.JANUARY, 1);
The month is zero based (0 = January, 1 = February,...). And this results in the output: Weekday of my Birthday: Sunday

How to use switch-statement correctly?

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

unable to use string.nextInt in string.hasNextLine loop

I need to create a program that receives the dates from file dates.txt and outputs them to dates.out, if the date is valid, then it will provide a new format and the day that the date falls in the year, if not it will return "Invalid date: (original date and format)" it seems that I have it all completed below, but I keep getting the error below when I type in the correct file name, im not sure what the problem is since I'm calling for a valid int.
view plainprint?
Note: Text content in the code blocks is automatically word-wrapped
Input file name: dates.txt
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Lab12.main(Lab12.java:43)
view plainprint?
Note: Text content in the code blocks is automatically word-wrapped
import java.io.*;
import java.util.*;
public class Lab12{
public static final int JAN = 1;
public static final int FEB = 2;
public static final int MAR = 3;
public static final int APR = 4;
public static final int MAY = 5;
public static final int JUN = 6;
public static final int JUL = 7;
public static final int AUG = 8;
public static final int SEP = 9;
public static final int OCT = 10;
public static final int NOV = 11;
public static final int DEC = 12;
public static void main(String[] arg)
throws FileNotFoundException{
Scanner console = new Scanner(System.in);
Scanner input = getInput(console);
while(input.hasNextLine()){
String text = input.nextLine();
Scanner time = new Scanner(text);
int day = time.nextInt(); // <<<< line 43
int month = time.nextInt();
int year = time.nextInt();
if(validDate(day, month, year)){
output.print (formatDate(day, month, year));
}
else
output.print ("Invalid date: "+day+"/"+month+"/"+year);
}
}
public static Scanner getInput(Scanner console)
throws FileNotFoundException{
System.out.print ("Input file name: ");
File f = new File(console.nextLine());
while(!f.canRead()){
System.out.println ("File not found. Try again.");
System.out.print ("Input file name: ");
f = new File(console.nextLine());
}
return new Scanner(f);
}
public static boolean isLeapYear(int year){
boolean isLeapYear = false;
if(year % 400 == 0)
isLeapYear = true;
else if(year % 4 == 0 && year % 100 == 0)
isLeapYear = false;
else if(year % 4 == 0)
isLeapYear = true;
else
isLeapYear = false;
return isLeapYear;
}
//http://www.java-forums.org/new-java/41020-day-number-count.html
public static int dayNumber(int day, int month, int year){
int daysInMonth = 0;
int days = 0;
boolean leapYear = isLeapYear(year);
for(int i = 1; i < month; i++){
switch(month){
case 1: daysInMonth += 31;
break;
case 2: if(leapYear)
daysInMonth = 29;
else
daysInMonth = 28;
break;
case 3: daysInMonth += 31;
break;
case 4: daysInMonth += 30;
break;
case 5: daysInMonth += 31;
break;
case 6: daysInMonth += 30;
break;
case 7: daysInMonth += 31;
break;
case 8: daysInMonth += 31;
break;
case 9: daysInMonth += 30;
break;
case 10: daysInMonth += 31;
break;
case 11: daysInMonth += 30;
break;
case 12: daysInMonth += 31;
break;
default:
break;
}
while(month <= 12){
days += days + daysInMonth + day;
month++;
}
}
return days;
}
public static boolean validDate(int day, int month, int year){
boolean validDate = false;
if(year >= 1 && year <= 3000){
if(month >= 1 && month <= 12){
if(month == 4 || month == 6 || month == 9 || month == 11
&& day >= 1 && day <= 30){
validDate = true;
}else if(month == 1 || month == 3 || month == 5 || month == 7
|| month == 8 || month == 10 || month == 12 &&
day <=31){
validDate = true;
}else if(month == 2){
boolean leapYear = isLeapYear(year);
if(leapYear = true && day >= 28){
validDate = false;
}
else if(leapYear = false && day <= 29){
validDate = true;
}
else{
validDate = true;
}
}
}
else
validDate = false;
}
else
validDate = false;
return validDate;
}
public static String formatDate(int day, int month, int year){
String formatDate = String.format ("%d-Jan-%d", day, year);
return formatDate;
}
}
content of dates.txt file
10/1/1999
12/31/2000
2/29/1900
2/1/1996
1/1/2097
2/29/2000
7/4/1776
5/32/3001
0/2/1234
8/0/2345
9/30/3001
2/29/2010
3/31/2001
13/3/1867
12/31/3000
You need to get the input as a String
"2/4/05" Them parse it
String dateString = input.nextLine();
String[] tokens = dateString.split("/");
int month = Integer.parseInt(tokens[0]);
int day = Integer.parseInt(tokens[1]);
int year = Integer.parseInt(tokens[2])
You're getting the error because of the /'s in the 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);

Categories