How do i take the user inputted day, month and year then store in a dd-mm-yyyy format? I can get everything to work except combining them into a date and storing them in the startDate variable. I also don't think startMonth will be accessible as it's in a switch case but I'm very new to java and unsure.
public static void carBookingDates() {
int carNumber;
int startYear;
int startDay;
int startMonth;
int daysInMonth = 0;
int endYear;
int endMonth;
int endDay;
Scanner input = new Scanner(System.in);
System.out.println("To make a booking:");
System.out.printf(" Select a car number from the car list: ");
carNumber = input.nextInt();
System.out.println("");
System.out.println("Enter a booking start date.");
System.out.printf("Please enter the year - for example '2022': ");
startYear = input.nextInt();
while (startYear < 2022 || startYear > 2030) {
System.out.println("Invalid year, please try again: ");
System.out.printf("Please enter the year - for example '2022': ");
startYear = input.nextInt();
}
System.out.printf("Please enter the month - for example '6': ");
startMonth = input.nextInt();
while (startMonth < 1 || startMonth > 12) {
System.out.println("Invalid month, please try again: ");
System.out.printf("Please enter the month - for example '6': ");
startMonth = input.nextInt();
}
switch (startMonth) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
daysInMonth = 31;
break;
case 4:
case 6:
case 9:
case 11:
daysInMonth = 30;
break;
case 2:
if (((startYear % 4 == 0)
&& !(startYear % 100 == 0))
|| (startYear % 400 == 0)) {
daysInMonth = 29;
} else {
daysInMonth = 28;
}
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.printf("Please enter the day number - for"
+ " example '18': ");
startDay = input.nextInt();
while (startDay > daysInMonth || startDay <= 0) {
System.out.println("Invalid day, plese try again");
System.out.printf("Please enter the day number - for"
+ " example '18': ");
startDay = input.nextInt();
LocalDate startDate() = LocalDate.parse(startDay + "-" + StartMonth "-" + startYear);
}
}
First of all, you can use the Java 8 Date Time API to get the number of days in a month instead of using a manual switch case for making the code more readable.
import java.time.YearMonth;
Then:
// 2021 is the year and 2 is the month
int daysInMonth = YearMonth.of(2021,2).lengthOfMonth());
Now to form the date in dd-mm-yyyy format :
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
Then:
// pass your date value here under LocalDate.of method
LocalDate.of(2021,2,16).format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
I need to know which day and day name is on a specific date. And somehow I made a mistake because for years with 19.. it works but at 2000 I can't get the right day anymore. For example if I use the date 9.1.2001 it doesn't say me the day, instead the error of the switch I made occurs.
and i shouldn't use the calendar methods
here is my code:
public class FindDay {
public static void main(String[] args) {
System.out.println("Type a day: ");
int day = In.readInt();
System.out.println("Type a month: ");
int month = In.readInt();
System.out.println("Type a year: ");
int year = In.readInt();
if(day < 1 || day > 32) {
System.out.println("Type valid day");
}else if (month < 1 || month >12) {
System.out.println("Type valid month");
}else if (year < 1900) {
System.out.println("Type valid year");
}
int wholeDaysYear; //to calculate how much days a year has
if (year % 4 == 0 && !(year % 100 == 0 && year % 400 != 0) ) {
wholeDaysYear = 366;
}else {
wholeDaysYear = 365;
}
int monthDays = 0; //calculates days to this month
int february; //if February has 28 or 2 days
if(wholeDaysYear ==366) {
february = 29;
}else {
february = 28;
}
switch(month) {
case 1: monthDays= 0; break;
case 2: monthDays =31; break;
case 3: monthDays= 31+february; break;
case 4: monthDays= 31+february+31; break;
case 5: monthDays= 31+february+31+30; break;
case 6: monthDays= 31+february+31+30+31; break;
case 7: monthDays= 31+february+31+30+31+30; break;
case 8: monthDays= 31+february+31+30+31+30+31; break;
case 9: monthDays= 31+february+31+30+31+30+31+31; break;
case 10: monthDays= 31+february+31+30+31+30+31+31+30; break;
case 11: monthDays= 31+february+31+30+31+30+31+31+30+31; break;
case 12: monthDays= 31+february+31+30+31+30+31+31+30+31+30; break;
default: System.out.println("Enter valid month!");break;
}
int leapYear = ((year-1) / 4 - 474) - ((year-1) / 100 - 18) + ((year-1) / 400 - 4); //calculates the leap years
int allDays =(((year - leapYear)-1900)*wholeDaysYear)+monthDays+day-1; //Calculates all days
System.out.println(allDays);
int dayName = allDays % 7;
String dayNames = null; //gives the days their name
switch (dayName) {
case 1: dayNames = "Monday";break;
case 2: dayNames = "Tuesday";break;
case 3: dayNames = "Wendesday";break;
case 4: dayNames = "Thursday";break;
case 5: dayNames = "Friday";break;
case 6: dayNames = "Saturday";break;
case 7: dayNames = "Sunday";break;
default: System.out.println("Type valid Input");break;
}
System.out.println(dayNames);
}
}
You don't have to work so hard... assuming you have the day of the month, month of the year and full-year, you can simply do (example):
LocalDate ld = LocalDate.of(1999, 12, 12);
System.out.println(ld.getDayOfWeek()); // prints SUNDAY
LocalDate is available since Java 8.
As for your code, two bugs that are easy to spot are:
The cases in the switch go from 1 to 7 while they should go from 0 to 6 since you're calculating the reminder out of 7.
int dayName = allDays % 7; here you assume that the first day of the year is Monday (according to your case switch) which is not necessarily true.
You can try something like this:
Date yourDate;
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH); //or Calendar.DAY_OF_WEEK
// etc.
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'm working on using enum / switch case along with Zeller's formula for saying what day of the year a specific date will be. My code was printing the right days before I implemented the enum / switch portion of my code (below). After I put in the enum/ switch case, when I run it in DrJava it does prompt for the day, the month and the year, but nothing prints once it goes through the switch case
import java.util.*;
public class Zeller {
public enum DaysOftheWeek {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
private static int value;
public Zeller (int value){
this.value = value;
}
public int getValue(){
return this.value;
}
public static void main(String[] args) {
DetermineDay(value); // Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a year, month and a day
System.out.print("Enter month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the day of the month: 1-31: ");
int day = input.nextInt();
System.out.print("Enter year (e.g., 2008): ");
int year = input.nextInt();
// Check if the month is January or February
// If the month is January and February, convert to 13, and 14,
// and year has to -1. (Go to previous year).
if (month == 1 || month == 2) {
month += 12;
year--;
}
// Compute the answer
int k = year % 100; // The year of the century
int j = (int)(year / 100.0); // the century
int q = day;
int m = month;
int h = (q + (int)((13 * (m + 1)) / 5.0) + k + (int)(k / 4.0)
+ (int)(j / 4.0) + (5 * j)) % 7;
value = h;
System.out.println(value);
}
public static String DetermineDay(int value){
String result = "Day of the week is ";
switch (value){
case 1 :
System.out.println(result + "Sunday");
break;
case 2 :
System.out.println(result + "Monday");
break;
case 3:
System.out.println(result + "Tuesday");
break;
case 4:
System.out.println(result + "Wednesday");
break;
case 5:
System.out.println(result + "Thursday");
break;
case 6:
System.out.println(result + "Friday");
break;
case 7 :
System.out.println( result + "Saturday");
break;
default :
System.out.println ("Looks like that day doesn't exist");
break;
}
return result;
}
}
If you want to output the day using DetermineDay you need to call that method at the end after you did the calculation and assigned the result to value.
This seems to work but there is a problem in your algorithm when trying this program with the date 4/11/2016 it does find that it is a Friday, but when using the date 5/5/2016 which is today the output is ¨Looks like that day doesn't exist¨, so yeah there is that.
At the end of DetermineDay you dont need to return a result since you already sop the result inside the switch.
import java.util.*;
public class Zeller {
public enum DaysOftheWeek {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
private static int value;
public Zeller (int value){
this.value = value;
}
public int getValue(){
return this.value;
}
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a year, month and a day
System.out.print("Enter month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the day of the month: 1-31: ");
int day = input.nextInt();
System.out.print("Enter year (e.g., 2008): ");
int year = input.nextInt();
// Check if the month is January or February
// If the month is January and February, convert to 13, and 14,
// and year has to -1. (Go to previous year).
if (month == 1 || month == 2) {
month += 12;
year--;
}
// Compute the answer
int k = year % 100; // The year of the century
int j = (int)(year / 100.0); // the century
int q = day;
int m = month;
int h = (q + (int)((13 * (m + 1)) / 5.0) + k + (int)(k / 4.0) + (int)(j / 4.0) + (5 * j)) % 7;
value = h;
System.out.println(value);
DetermineDay(value);
}
public static void DetermineDay(int value){
String result = "Day of the week is ";
switch (value){
case 1 :
System.out.println(result + "Sunday");
break;
case 2 :
System.out.println(result + "Monday");
break;
case 3:
System.out.println(result + "Tuesday");
break;
case 4:
System.out.println(result + "Wednesday");
break;
case 5:
System.out.println(result + "Thursday");
break;
case 6:
System.out.println(result + "Friday");
break;
case 7 :
System.out.println( result + "Saturday");
break;
default :
System.out.println ("Looks like that day doesn't exist");
break;
}
}
}
I have a project due soon. We have to write a program that asks for a year and prints out a calendar. We can only use one while, one for, and one switch loop. (and no arrays! ugh) Im having trouble figuring out how to print out the days of each month, starting with the first day of the first week, as most months will not start on Sunday.
import java.util.*;
import java.util.Calendar;
class Lab2 {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
System.out.print("What year do you want to view? ");
int year = user.nextInt();
System.out.printf("%12d\n", year);
System.out.println();
boolean leap = isLeap(year);
int firstDay = JulianDate(year);
monthLoop(year, firstDay, leap);
}
public static boolean isLeap(int year) {
boolean verdict = false;
if (year % 100 == 0 && year % 400 == 0) {
verdict = true;
}
if(year % 100 != 0 && year % 4 == 0) {
verdict = true;
}
return verdict;
}
public static int JulianDate(int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_YEAR, 1);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
return dayOfWeek;
}
public static void monthLoop(int year, int firstDay, boolean leap) {
for(int i=1; i <= 12; i++) {
switch (i) {
case 1: System.out.printf("%13s\n", "January");
break;
case 2: System.out.printf("%13s\n", "February");
break;
case 3: System.out.printf("%12s\n", "March");
break;
case 4: System.out.printf("%12s\n", "April");
break;
case 5: System.out.printf("%11s\n", "May");
break;
case 6: System.out.printf("%11s\n", "June");
break;
case 7: System.out.printf("%11s\n", "July");
break;
case 8: System.out.printf("%13s\n", "August");
break;
case 9: System.out.printf("%14s\n", "September");
break;
case 10: System.out.printf("%13s\n", "October");
break;
case 11: System.out.printf("%14s\n", "November");
break;
case 12: System.out.printf("%14s\n", "December");
break;
}
System.out.println("S M Tu W Th F S");
}
}
}
You would get the day of the week, as in this post, of the first day of the month and then start the counter from there.
How to get the day of the week in Java
For instance, if the day of the week was 5, you would put 4 "blanks" before the first date. The trick is that when you are doing your mod, to determine if there should be a new line, it would be
(dayofMonth + firstDayOfWeekOfMonth) % 7