How I can match jalili calender with hijri calendar - java

I want to show jalali calendar and hijri calendar at the same time, but i don't know how to match jalali days with hijri days. I searched and found the source code below. It shows jalali calendar but I don't know how to match two calendars. Hijri calendar does'nt have any specific pattern for months.
import javax.swing.JOptionPane;
public class TestCal {
/** Main method */
public static void main(String[] args) {
// Prompt the user to enter year
String yearString = JOptionPane.showInputDialog(
"Lotfan Sale morede nazar ra vared konid (Masalan 1390):");
// Convert string into integer
int year = Integer.parseInt(yearString);
// Prompt the user to enter month
String monthString = JOptionPane.showInputDialog(
"Lotfan mahe khod ra niz az miane adade 1 ta 12 bargozinid:");
// Convert string into integer
int month = Integer.parseInt(monthString);
// Print calendar for the month of the year
printMonth(year, month);
}
/** Print the calendar for a month in a year */
static void printMonth(int year, int month) {
// Print the headings of the calendar
printMonthTitle(year, month);
// Print the body of the calendar
printMonthBody(year, month);
}
/** Print the month title, e.g., May, 1999 */
static void printMonthTitle(int year, int month) {
System.out.println(" " + getMonthName(month)
+ " " + year);
System.out.println("-----------------------------");
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
}
/** Get the English name for the month */
public static String getMonthName(int month) {
String monthName = null;
switch (month) {
case 1: monthName = "Farvardin"; break;
case 2: monthName = "Ordibehesht"; break;
case 3: monthName = "Khordad"; break;
case 4: monthName = "Tir"; break;
case 5: monthName = "Mordad"; break;
case 6: monthName = "Shahrivar"; break;
case 7: monthName = "Mehr"; break;
case 8: monthName = "Aban"; break;
case 9: monthName = "Azar"; break;
case 10: monthName = "Dey"; break;
case 11: monthName = "Bahman"; break;
case 12: monthName = "Esfand";
}
return monthName;
}
/** Print month body */
public static void printMonthBody(int year, int month) {
// Get start day of the week for the first date in the month
int startDay = getStartDay(year, month);
// Get number of days in the month
int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month);
// Pad space before the first day of the month
int i = 0;
for (i = 0; i < startDay; i++)
System.out.print(" ");
for (i = 1; i <= numberOfDaysInMonth; i++) {
if (i < 10)
System.out.print(" " + i);
else
System.out.print(" " + i);
if ((i + startDay) % 7 == 0)
System.out.println();
}
System.out.println();
}
/** Get the start day of the first day in a month */
public static int getStartDay(int year, int month) {
// Get total number of days since 1/1/1800
int startDay1300 = 1;
int totalNumberOfDays = getTotalNumberOfDays(year, month);
// Return the start day
return (totalNumberOfDays + startDay1300) % 7;
}
/** Get the total number of days since Jan 1, 1800 */
static int getTotalNumberOfDays(int year, int month) {
int total = 0;
// Get the total days from 1800 to year - 1
for (int i = 1300; i < year; i++)
if (isLeapYear(i))
total = total + 366;
else
total = total + 365;
// Add days from Jan to the month prior to the calendar month
for (int i = 1; i < month; i++)
total = total + getNumberOfDaysInMonth(year, i);
return total;
}
/** Get the number of days in a month */
public static int getNumberOfDaysInMonth(int year, int month) {
if (month <= 6 && month > 0)
return 31;
else if (month < 12 && month > 6)
return 30;
if (month == 12) return isLeapYear(year) ? 30 : 29;
return 0; // If month is incorrect
}
/** Determine if it is a leap year */
public static boolean isLeapYear(int year) {
return year % 400 == 0 || (year % 4 == 3 && year % 100 != 0);
}
}

A very simple approach:
Take a common epoch between two calendars
Develop/Find algorithms to convert calendar date to/from number of days between that epoch.
Convert date from calendar type A to epoch-delta and epoch-delta to calendar type B.
I have implemented a simple C library to convert between dates in various calendars. The code is available here. You can extract algorithms and implement them in your own language of choice. In case you are using C/C++, you can simply:
#include <calendars/cl-calendar.h>
int16_t year;
uint8_t month;
uint16_t day;
convert_date(CAL_ISLAMIC_CIVIL, CAL_SOLAR_HIJRI,
1396, 7, 11, &year, &month, &day);
printf("1396/07/11 AP is: %d/%d/%d Hijri", year, month, day);
which will print:
$ 1396/07/11 AP is: 1439/1/12 Hijri
Notes:
Jalali calendar is not being used anymore. You probably want to use Solar Hijri Calendar.
Hijri Calendar is not tabular. You probably mean Islamic Civil Clanndar

Related

An effective way of making a dedicated calendar for a month in java programming

I need some help; I've been stuck with this situation for a while. My goal is to display a calendar form for the month of August 2021. I have my code here. I only need the month of August since I just want to post a calendar of the month for users to see the date for the opening of classes. It displays the calendar, but I feel it has a more efficient way of writing this type of program, but I don't know how. Can you please help me?
Here is my code:
public class Calendar {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("\t\tMONTH OF AUGUST 2021");
System.out.println("–––––––––––––––-------------------------––––––––––––––");
System.out.println("\nSun\tMon\tTue\tWed\tThu\tFri\tSat\n");
System.out.println("–––––––––––––––-------------------------––––––––––––––");
int [][]num={{1,2,3,4,5,6,7},{8,9,10,11,12,13,14},{15,16,17,18,19,20,21},{22,23,24,25,26,27,28},{29,30,31,1,2,3,4}};
for (int i=1; i<num.length;i++){
for(int j=8; j<num[i].length; j++){
num[i][j]=i+j;
}
}
for(int[] a: num){
for(int i:a){
System.out.print(i + "\t");
}
System.out.println("\n");
}
}
}
To display a calendar in the Console window (and it shouldn't matter what month) then you can do it with this java method:
public static void displayConsoleCalendar(int day, int month, int year,
boolean... useColorCodes) {
boolean useColor = false;
if (useColorCodes.length > 0) {
useColor = useColorCodes[0];
}
String red = "\033[0;31m";
String blue = "\033[0;34m";
String reset = "\033[0m";
java.util.Calendar calendar = new java.util.GregorianCalendar(year, month - 1, day + 1);
calendar.set(java.util.Calendar.DAY_OF_MONTH, 1); //Set the day of month to 1
int dayOfWeek = calendar.get(java.util.Calendar.DAY_OF_WEEK); //get day of week for 1st of month
int daysInMonth = calendar.getActualMaximum(java.util.Calendar.DAY_OF_MONTH);
//print month name and year
System.out.println(new java.text.SimpleDateFormat("MMMM YYYY").format(calendar.getTime()));
System.out.println((useColor?blue:"") + " S M T W T F S" + (useColor?reset:""));
//print initial spaces
String initialSpace = "";
for (int i = 0; i < dayOfWeek - 1; i++) {
initialSpace += " ";
}
System.out.print(initialSpace);
//print the days of the month starting from 1
for (int i = 0, dayOfMonth = 1; dayOfMonth <= daysInMonth; i++) {
for (int j = ((i == 0) ? dayOfWeek - 1 : 0); j < 7 && (dayOfMonth <= daysInMonth); j++) {
if (dayOfMonth == day && useColor) {
System.out.printf(red + "%2d " + reset, dayOfMonth);
}
else {
System.out.printf("%2d ", dayOfMonth);
}
dayOfMonth++;
}
System.out.println();
}
}
If your terminal supports escape color codes then the day you supplied would be red within the calendar. This method also takes care of leap years. Just provide the integer values for day, month, and year as arguments. The last parameter to apply color codes is optional.
If you want to display the month of August and you want the 20th of that month to be highlighted in red then you would make the following call:
displayConsoleCalendar(20, 8, 2021, true);
The console window may display something like this:
To come up with this solution (linear time complexity):
run a for loop with i from 0 to 34
print a new line only when i != 0 && i % 7 == 0
use i % 31 + 1 on the current number i to keep it within bounds
public static void main(String[] args) {
System.out.println("\t\tMONTH OF AUGUST 2021");
System.out.println("–––––––––––––––-------------------------––––––––––––––");
System.out.println("\nSun\tMon\tTue\tWed\tThu\tFri\tSat\n");
System.out.println("–––––––––––––––-------------------------––––––––––––––");
for(int i = 0; i < 35; i++) {
if(i!= 0 && i % 7 == 0)
System.out.println("\n");
System.out.print(i % 31 + 1 + "\t");
}
}
There is a complex and shorter version for this (for curious people)
while(i < 35)
System.out.print(
((i != 0 && i % 7 == 0) ? "\n": "")
+ (i++ % 31 + 1)
+ "\t"
);
Here's an alternative that isn't actually more elegant or efficient, but uses a different approach (different library), and it supports different languages:
public static void printCalendarFor(int month, int year, Locale locale) {
// build the given month of the given year
YearMonth yearMonth = YearMonth.of(year, month);
// extract its name in the given locale
String monthName = yearMonth.getMonth().getDisplayName(TextStyle.FULL, locale);
// create a builder for the calendar
StringBuilder calendarBuilder = new StringBuilder();
// and append a header with the month name and the year
calendarBuilder.append("\t\t ").append(monthName).append(" ").append(year).append(System.lineSeparator());
// then append a second header with all the days of week
calendarBuilder.append(DayOfWeek.MONDAY.getDisplayName(TextStyle.SHORT, locale)).append("\t")
.append(DayOfWeek.TUESDAY.getDisplayName(TextStyle.SHORT, locale)).append("\t")
.append(DayOfWeek.WEDNESDAY.getDisplayName(TextStyle.SHORT, locale)).append("\t")
.append(DayOfWeek.THURSDAY.getDisplayName(TextStyle.SHORT, locale)).append("\t")
.append(DayOfWeek.FRIDAY.getDisplayName(TextStyle.SHORT, locale)).append("\t")
.append(DayOfWeek.SATURDAY.getDisplayName(TextStyle.SHORT, locale)).append("\t")
.append(DayOfWeek.SUNDAY.getDisplayName(TextStyle.SHORT, locale)).append(System.lineSeparator());
// get the first day of the given month
LocalDate dayOfMonth = yearMonth.atDay(1);
// and go through all the days of the month handling each day
while (!dayOfMonth.isAfter(yearMonth.atEndOfMonth())) {
// in order to fill up the weekday table's first line, specially handle the first
if (dayOfMonth.getDayOfMonth() == 1) {
switch (dayOfMonth.getDayOfWeek()) {
case MONDAY:
calendarBuilder.append(String.format("%3d", dayOfMonth.getDayOfMonth()))
.append("\t");
break;
case TUESDAY:
calendarBuilder.append("\t")
.append(String.format("%3d", dayOfMonth.getDayOfMonth()))
.append("\t");
break;
case WEDNESDAY:
calendarBuilder.append("\t\t")
.append(String.format("%3d", dayOfMonth.getDayOfMonth()))
.append("\t");
break;
case THURSDAY:
calendarBuilder.append("\t\t\t")
.append(String.format("%3d", dayOfMonth.getDayOfMonth()))
.append("\t");
break;
case FRIDAY:
calendarBuilder.append("\t\t\t\t")
.append(String.format("%3d", dayOfMonth.getDayOfMonth()))
.append("\t");
break;
case SATURDAY:
calendarBuilder.append("\t\t\t\t\t")
.append(String.format("%3d", dayOfMonth.getDayOfMonth()))
.append("\t");
break;
case SUNDAY:
calendarBuilder.append("\t\t\t\t\t\t")
.append(String.format("%3d", dayOfMonth.getDayOfMonth()))
.append(System.lineSeparator());
break;
}
} else {
// for all other days, just append their numbers
calendarBuilder.append(String.format("%3d", dayOfMonth.getDayOfMonth()));
// end the line on Sunday, otherwise append a tabulator
if (dayOfMonth.getDayOfWeek() == DayOfWeek.SUNDAY) {
calendarBuilder.append(System.lineSeparator());
} else {
calendarBuilder.append("\t");
}
}
// finally increment the day of month
dayOfMonth = dayOfMonth.plusDays(1);
}
// print the calender
System.out.println(calendarBuilder.toString());
}
Here's some example use
public static void main(String[] args) {
printCalendarFor(8, 2021, Locale.ENGLISH);
}
The output of that example use is
August 2021
Mon Tue Wed Thu Fri Sat Sun
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

How to reset int values

Trying to write a code for my intro to java course but unable to reset int value.
For my intro course, I have to write a program that determines a due date based on the type of book the user is checking out. I am not allowed to use any date formats, just simply inputting month day and year as integers.
The main part of this program is that new books have a 14 day check out and non -new books have a 21 day check out limit. I have figured out how to add the specified number of days based on the type of book, but given that days, months and year are defined as integers, how would I reset the days if the inputted date of the check out exceeds the number of day within that particular month?
I know how to format it to display it continuing over to the next month. But say the user inputs the check out day is the 15 of February, how would my program know how to restart counting on the next month but also know when it's reaching its limit of either 14 or 21 days?
String releaseType;
int coMonth, coYear;
int coDays = 0;
// determing how many days added to due date
if (releaseType == "NEW"){
coDays += 14;
}else{
coDays += 21;
}
if (coDays > 30){
coMonth +=1;
}
if (coMonth >12){
coYear +=1;
}
System.out.println("You due date is " + coMonth + "/" + coDays + "/" + coYear);
Input data: NEW, 2 (month) 15 (day) 2019 (year)
output: You due date is 3/36/2019
Below is the outline for a class that should do what you want.
class Date
{
Date(int InputDay, int InputMonth, int InputYear;
{
Day = InputDay;
Month = InputMonth;
Year = InputYear;
}
public final int GetDay()
{
return Day;
}
public final int GetMonth()
{
return Month;
}
public final int GetYear()
{
return Year;
}
// Increments the current date by NumDays.
public final Date AddDays(int NumDays)
{
int TempDay = Day;
int TempMonth = Month;
int TempYear = Year;
while (NumDays > 0)
{
switch (Month)
{
case 1: // Jan
{
TempDay += NumDays;
if (TempDay > 31)
{
NumDays = TempDay - 31;
TempDay = 1;
TempMonth++;
}
else
{
NumDays = 0;
}
} break;
case 2: // Feb
{
TempDay += NumDays;
if (TempDay > 28 && IsLeapYear() == false)
{
NumDays = TempDay - 28;
TempDay = 1;
TempMonth++;
}
else if (TempDay > 29 && IsLeapYear() == true)
{
NumDays = TempDay - 29;
TempDay = 1;
TempMonth++;
}
else
{
NumDays = 0;
}
} break;
// Fill in the rest of the months. I've done the
// important ones.
case 12: // Dec
{
TempDay += NumDays;
if (TempDay > 31)
{
NumDays = TempDay - 31;
TempDay = 1;
TempMonth = 1;
TempYear++;
}
else
{
NumDays = 0;
}
} break;
} // End switch
} // End while loop
return new Date(TempDay, TempMonth, TempYear);
}
private boolean IsLeapYear()
{
boolean LeapYear = false;
// Note: In the Gregorian calendar, it is also a leap year if the
// year is divisible by 400 but it's not a leap year if it is
// divisible by 100.
if ( (Year % 4 == 0 && Year % 100 != 0) || Year % 400 == 0)
{
LeapYear = true;
}
return LeapYear;
}
private final int Day;
private final int Month; // Range: 1 - 12
private final int Year;
}
It would be used as follows:
Date Today = new Date(7,10,2019), DueDate;
DueDate = Today.AddDays(21);

"How to fix 'class, interface, or enum expected' for my code

I am unable to find the solution for my code, I receive a 'class, interface, or enum expected' when trying to compile my code.
I have tried to research on how to fox the problem but I was unfortunately unable to do so as it seems like nothing is working for me...also if there are any errors that would lead up to it not working once this part is fixed, please let me know as to what I can change!
The code:
class MyDate {
//properties of date object
private int day, month, year;
//Constructor with arguments
public MyDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public boolean isValidDate() {
if (month > 12 || month < 1 || day < 1) { // if negative values found
return false;
} else if (year <= 1582 && month <= 10 && day <= 15) { // starting date
// checking
return false;
} // for 31 day months
else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
if (day > 31) {
return false;
}
} // for 30 day months
else if (month == 4 || month == 6 || month == 9 || month == 11) {
if (day > 30) {
return false;
}
} else if (month == 2) // February check
{
if (isLeapYear()) // Leap year check for February
{
if (day > 29) {
return false;
}
} else {
if (day > 28) {
return false;
}
}
}
return true;
}
// checks if this year is leap year
private boolean isLeapYear() {
if (year % 4 != 0) {
return false;
} else if (year % 400 == 0) {
return true;
} else if (year % 100 == 0) {
return false;
} else {
return true;
}
}
/**
* #return the day
*/
public int getDay() {
return day;
}
/**
* #param day
* the day to set
*/
public void setDay(int day) {
this.day = day;
}
/**
* #return the month
*/
public int getMonth() {
return month;
}
/**
* #param month
* the month to set
*/
public void setMonth(int month) {
this.month = month;
}
/**
* #return the year
*/
public int getYear() {
return year;
}
/**
* #param year
* the year to set
*/
public void setYear(int year) {
this.year = year;
}
#Override
public String toString() {
return day + "/" + month + "/" + year;
}
}
import java.util.Scanner;
public class MyCalendar {
//enums for days of week
public static enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
};
//enum for month of year
public static enum Month {
JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER,
OCTOBER, NOVEMBER, DECEMBER;
};
//enums for week numbers
public static enum Week { FIRST, SECOND, THIRD, FOURTH;
};
//to store Date object
private MyDate date;
//constructor taking mydate object
public MyCalendar(MyDate enteredDate) {
this.date = enteredDate;
}
//main method
public static void main(String[] args) {
boolean validDate = false; //valid date false
Scanner input = new Scanner(System.in); //scanner for input
MyDate enteredDate = null;
//till valid date found
while (!validDate) {
System.out.print("Enter the date as day month year : ");
//taking input and creating date object
enteredDate = new MyDate(input.nextInt(), input.nextInt(),
input.nextInt());
//validdating date object
if (enteredDate.isValidDate()) { //if valid
MyCalendar myCalendar = new MyCalendar(enteredDate); //creating
calendar object
myCalendar.printDateInfo(); //printing date info
myCalendar.printCalendar(); //printing calendar
validDate = true; //setting validate to true
} else {
System.out.println("Please enter a Valid Date...");
}
}
input.close();
}
// returns number of days in current month
private int getNumberOfDays() {
int days = 31;
int month = date.getMonth();
if (month == 4 || month == 6 || month == 9 || month == 11)
days = 30;
return days;
}
//print calendar of this month
public void printCalender() {
System.out.println("\n\nThe Calendar of "+Month.values()
[date.getMonth()-1]+" "+date.getYear()+" is :");
int numberOfMonthDays = getNumberOfDays();
Day firstWeekdayOfMonth = getDayOfWeek(1, date.getMonth(),
date.getYear());
int weekdayIndex = 0;
System.out.println("SUN MON TUE WED THU FRI SAT"); // The order of days
// depends on your
// calendar
for (int day = 0; Day.values()[day] != firstWeekdayOfMonth; day++) {
System.out.print(" "); // this loop to print the first day in
his
// correct place
weekdayIndex++;
}
for (int day = 1; day <= numberOfMonthDays; day++) {
if (day < 10)
System.out.print(day + " ");
else
System.out.print(day);
weekdayIndex++;
if (weekdayIndex == 7) {
weekdayIndex = 0;
System.out.println();
} else {
System.out.print(" ");
}
}
System.out.println();
}
//method to print about date information in literal form
public void printDateInfo() {
System.out.println(date + " is a " + getDayOfWeek(date.getDay(),
date.getMonth(), date.getYear())
+ " located in the " + Week.values()[getWeekOfMonth() - 1] + "
week of "
+ Month.values()[date.getMonth() - 1] + " " + date.getYear());
}
/*
* gets day of the week, returns enum type Day
*
* day of week (h) = (q+(13*(m+1)/5)+K+(K/4)+(J/4)+5J)%7 ,q- day of month,
* m- month, k = year of century (year%100), J = (year/100)
*/
public Day getDayOfWeek(int day, int month, int year) {
int q = day;
int m = month;
if (m < 3) {
m = 12 + date.getMonth();
year = year - 1;
}
int K = year % 100;
int J = year / 100;
//calculating h value
int h = (q + (13 * (m + 1) / 5) + K + (K / 4) + (J / 4) + 5 * J) % 7;
Day output = null;
if (h < Day.values().length && h >= 0) {
output = Day.values()[h - 1]; //getting respective enum value
}
return output; //returning enum value
}
// get week number of current date
public int getWeekOfMonth() {
int days = date.getDay();
int weeks = days / 7;
days = days % 7;
if (days > 0)
weeks++;
return weeks;
}
}
The error:
MyCalendar.java:120: class, interface, or enum expected
import java.util.Scanner;
^
Error given when I move the import to the top (UPDATED):
MyCalendar.java:164: cannot find symbol
symbol : method printCalendar()
location: class MyCalendar
myCalendar.printCalendar(); //printing calendar
Expected code:
java MyCalendar 29/02/2019
29/02/2019 in not a valid date, please re-input a valid date: 25/05/2019
25/05/2019 is a Saturday and located in the fourth week of May 2019
The calendar of May 2019 is:
SUN MON TUE WED THU FRI SAT
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
the method public void printCalender() should be called or invoked as printCalender() not as printCalendar()
your method is printCalender() whereas you are calling printCalendar() which does not exist.

How to calculate no of days in a month? User to enter the no of the month [duplicate]

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

Output not printing after switch case utilized Java

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

Categories

Resources