Related
I'm trying to get the amount of days until the meeting to go back and print out the day the new meeting is on but I keep getting an integer instead of the string.
import java.util.Scanner;
public class NextMeeting {
public static void main(String [] args) {
int day, daysToMeeting = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the day of the week 0-6: ");
day = scan.nextInt();
System.out.println("Enter the days to meeting: ");
daysToMeeting = scan.nextInt();
if (day == 0) {
System.out.println("Today is Sunday");
} else if (day == 1) {
System.out.println("Today is Monday");
}
else if (day == 2) {
System.out.println("Today is Tuesday");
}
else if (day == 3) {
System.out.println("Today is Wednesday");
}
else if (day == 4) {
System.out.println("Today is Thursday");
}
else if (day == 5) {
System.out.println("Today is Friday");
}
else if (day == 6) {
System.out.println("Today is Saturday");
}
System.out.println("Today is: " + day);
if( daysToMeeting >= 6) {
day = daysToMeeting - 7;
}
else {
day = day + 6;
}
System.out.println("Days to the meeting is " + daysToMeeting + " +days.");
System.out.println("Meeting day is : " + Integer.toString(day));
}
}
The output for days is still 3 but we need to get it to print out Wednesday. I don't know how to make that happen.
You can use DayOfWeek enum.
System.out.println("Meeting day is : " + DayOfWeek.of(day).toString());
You can also remove nested if-else statement and use DayOfWeek enum to display "Today is xyz-day".
You are printing out integers because day is an int. It may be inefficient but an easy fix is to create a String variable and in another if-statement block below the daysToMeeting if-else block, assign the String to each corresponding integer, such as
String meetingDay;
if(day == 1){
meetingDay = "Monday";
}
and then print out using the String variable.
System.out.println("Meeting day is : " + meetingDay);
Just create a method which will return the day of week String by passing the day int. Then print the result.
public String intToDayName(int day) {
if(day > 6) {
day = day % 7;
}
if (day == 0) {
return "Sunday";
} else if (day == 1) {
return "Monday";
}
else if (day == 2) {
return "Tuesday";
}
else if (day == 3) {
return "Wednesday";
}
else if (day == 4) {
return "Thursday";
}
else if (day == 5) {
return "Friday";
}
else if (day == 6) {
return "Saturday";
}
return "Error";
}
calling it in your prints:
System.out.println("Meeting day is : " + intToDayName(daysToMeeting));
System.out.println("Today is " + intToDayName(day));
If you actually want your code to go back and print the first if-else statements then I suggest looping.
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);
I am really new to Java, and I am writing a Java program that reads dates in the format mm/dd/yyyy and prints out the date in the format day, year. The program must verify that the year is between 1900 and 2014 (both limits included) and that the day and month and year are valid and mutually consistent. If the input is incorrect, the program must display an appropriate message and terminate. If the input is correct, the output should be printed in the specified format.
For Example:
Enter Date
04/30/2013
April 30, 2013
Enter Date
01/12/1888
Year should be between 1900 and 2014
I am stuck at how to limit the year and days (like February only has 28), and how to print out like the examples above. I am suppose to use if else and switch statement for this problem. Here is the code i got so far, and thanks for your help.
import java.util.Scanner;
public class Dates {
public static void main(String[] args) {
int month, day, year;
Scanner input = new Scanner(System.in);
System.out.print("Please Enter Date in The Format mm/dd/yyyy : ");
month = input.nextInt();
day = input.nextInt();
year = input.nextInt();
String months = "January February March April May June July August "
+ "September October November December";
String January = months.substring(0,7);
String February = months.substring(8,16);
String March = months.substring(17,22);
String April = months.substring(23,28);
String May = months.substring(29,32);
String June = months.substring(33,37);
String July = months.substring(38,42);
String August = months.substring(43,49);
String September = months.substring(50,59);
String October = months.substring(60,67);
String November = months.substring(68,76);
String December = months.substring(77,85);
if (month == 1) {
months = January;
day = 31;
}
else if (month == 2) {
months = February;
day = 28;
}
else if (month == 3) {
months = March;
day = 31;
}
else if (month == 4) {
months = April;
day = 30;
}
else if (month == 5) {
months = May;
day = 31;
}
else if (month == 6) {
months = June;
day = 30;
}
else if (month == 7) {
months = July;
day = 31;
}
else if (month == 8) {
months = August;
day = 31;
}
else if (month == 9) {
months = September;
day = 30;
}
else if (month == 10) {
months = October;
day = 31;
}
else if (month == 11) {
months = November;
day = 30;
}
else if (month == 12) {
months = December;
day = 31;
}
else {
System.out.print("Invalid Month");
}
if (year >= 1900 || year <= 2014) {
System.out.print(year);
}
else {
System.out.println("Year should be between 1900 and 2014");
}
System.out.println(months + " " + day + ", " + year);
}
}
Use Calendar and SimpleDateFormat for working and formatting dates respectively in Java. That's the good choice! Please don't reinvent the wheel unless you are in your learning process.
Please read the documentation of Calendar and SimpleDateFormat API
You should use a SimpleDateFormat, and you can verify with a Calendar.
You should try using the classes Calendar, GregorianCalendar and SimpleDateFormat
You should use GregorianCalendar for formatting.
You have to skip the '/' character before reading another Integer.
/*month = input.nextInt();
day = input.nextInt();
year = input.nextInt();*/
String dummy = input.nextLine();
month = Integer.parseInt(dummy.substring(0, 2));
day = Integer.parseInt(dummy.substring(3, 5));
year = Integer.parseInt(dummy.substring(6, 10));
You last line is wrong
System.out.println(months + " " + day + ", " + year);
For Leap year stuff, you should visit the wiki.
http://en.wikipedia.org/wiki/Leap_year#Algorithm
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);
I am trying to calculate the current age of a user .. but using the format i would like to use has caused some issues for me .
I could just ask separately for the year , month and day but much rather prefer (mm/dd/yyyy)
//Need help turning (mm/dd/yyyy) that the user inputs into:
//yyyy;
//mm;
// dd;
package org.joda.time;
import java.util.Calendar;
import java.util.GregorianCalendar;//needed for leap year
import java.util.Scanner;
import java.io.*;
public class AgeCalculation{
public static void main(String[] args) throws IOException{
int day = 1, month = 0, year = 1, ageYears, ageMonths, ageDays;
Scanner myScanner = new Scanner(System.in);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Calendar cd = Calendar.getInstance();
try{
System.out.print("Enter your Date of Birth.(mm/dd/yyyy): ");
Dob = myScanner.nextLine() ;
// how to get year , month and date from (mm/dd/yyyy) format?
year = ;
if(year > cd.get(Calendar.YEAR)){
System.out.print("Invalid date of birth.");
System.exit(0);
}
month =
if(month < 1 || month > 12){
System.out.print("Please enter monthe between 1 to 12.");
System.exit(0);
}
else{
month--;
if(year == cd.get(Calendar.YEAR)){
if(month > cd.get(Calendar.MONTH)){
System.out.print("Invalid month!");
System.exit(0);
}
}
}
if(month == 0 || month == 2 || month == 4 || month == 6 || month == 7 ||
month == 9 || month == 11){
if(day > 31 || day < 1){
//leap year data below
System.out.print("Please enter day between 1 to 31.");
System.exit(0);
}
}
else if(month == 3 || month == 5 || month == 8 || month == 10){
if(day > 30 || day < 1){
System.out.print("Please enter day between 1 to 30.");
System.exit(0);
}
}
else{
if(new GregorianCalendar().isLeapYear(year)){
if(day < 1 || day > 29){
System.out.print("Please enter day between 1 to 29.");
System.exit(0);
}
}
else if(day < 1 || day > 28){
System.out.print("Please enter day between 1 to 28.");
System.exit(0);
}
}
if(year == cd.get(Calendar.YEAR)){
if(month == cd.get(Calendar.MONTH)){
if(day > cd.get(Calendar.DAY_OF_MONTH)){
System.out.print("Invalid date!");
System.exit(0);
}
}
}
}
catch(NumberFormatException ne){
System.out.print(ne.getMessage() + " is not a legal entry!");
System.out.print("Please enter number.");
System.exit(0);
}
Calendar bd = new GregorianCalendar(year, month, day);
ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
if(cd.before(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))){
ageYears--;
ageMonths = (12 - (bd.get(Calendar.MONTH) + 1)) + (bd.get(Calendar.MONTH));
if(day > cd.get(Calendar.DAY_OF_MONTH)){
ageDays = day - cd.get(Calendar.DAY_OF_MONTH);
}
else if(day < cd.get(Calendar.DAY_OF_MONTH)){
ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
}
else{
ageDays = 0;
}
}
else if(cd.after(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))){
ageMonths = (cd.get(Calendar.MONTH) - (bd.get(Calendar.MONTH)));
if(day > cd.get(Calendar.DAY_OF_MONTH))
ageDays = day - cd.get(Calendar.DAY_OF_MONTH) - day;
else if(day < cd.get(Calendar.DAY_OF_MONTH)){
ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
}
else
ageDays = 0;
}
else{
ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
ageMonths = 0;
ageDays = 0;
}
System.out.print("Age of the person : " + ageYears + " year, " + ageMonths +
" months and " + ageDays + " days.");
}
}
Here's a hint as how you could read in and parse the entered date:
SimpleDateFormat f = new SimpleDateFormat("MM/dd/yyyy"); //note that mm is minutes, so you need MM here
Scanner s = new Scanner( System.in );
String dateLine = s.nextLine();
try
{
Date d = f.parse( dateLine );
System.out.println(d);
}
catch( ParseException e )
{
System.out.println("please enter a valid date in format mm/dd/yyyy");
}
That's just an example and should get you started with reading the date correctly.
For getting the years, days and months in between two dates I'd still recommend using JodaTime since that makes life much easier.
Using standard Java facilities, this could help you:
Calendar c = Calendar.getInstance();
c.setTimeInMillis( System.currentTimeMillis() - d.getTime() );
System.out.println( c.get( Calendar.YEAR ) - 1970 ); //since year is based on 1970, subtract that
System.out.println( c.get( Calendar.MONTH ) );
System.out.println( c.get( Calendar.DAY_OF_MONTH ) );
Note that you need to subtract the smaller date from the bigger, i.e. the difference must be positive (which should be true when subtracting birth dates from the current time).
This would give a difference of 0 years, 9 full months and 26 days between Jan 1st 2011 and Oct 26th 2011, and a difference of 21 years and 1 day (since we already started this day) between Oct 26th 1990 and Oct 26th 2011.
If you want to use JodaTime:
String dob = myScanner.nextLine();
DateTimeFormatter format = DateTimeFormatter.forPattern("MM/dd/yyyy");
DateTime dateTimeOfBirth = DateTime.parse(dob, format);
year = dateTimeOfBirth.getYear();
// Etc
try this, it out puts the age into a form field called age in a form called "form", assumes you called your textbox(where DOB is entered) "dob"
var d =document.getElementById('dob').value.split('/');
var today = new Date();
var bday = new Date(d[2],d[1],d[0]);
var age = today.getFullYear() - bday.getFullYear();
if(today.getMonth() < bday.getMonth() || (today.getMonth() == bday.getMonth() && today.getDate() < bday.getDate()))
{
t = age--;
}
else {
t = age
}
form.age.value = t;
}
You'll pobably need something like that:
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy", Locale.US);
Date date = sdf.parse(timestamp);
Calendar cd = Calendar.getInstance();
cd.setTime(date);