Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I know how to create normal calendar which would be something like this.
code:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class CalendarDateExample {
public static void main(String[] args) {
// Create an instance of a GregorianCalendar
Calendar calendar = new GregorianCalendar(2014, 1, 06);
System.out.println("Year: " + calendar.get(Calendar.YEAR));
System.out.println("Month: " + (calendar.get(Calendar.MONTH) + 1));
System.out.println("Day: " + calendar.get(Calendar.DAY_OF_MONTH));
// Format the output.
SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(date_format.format(calendar.getTime()));
}
}
Output :
Year: 2014
Month: 2
Day: 6
2014-02-06
But how would display a calender for given month and year making it look like:
July 2005
S M T W Th F S
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
I am new to java , would like know how to do it the way above. any help would be great!
thanks in advance
You could do this:
Calendar calendar = new GregorianCalendar(2014, 1, 06);
calendar.set(Calendar.DAY_OF_MONTH, 1); //Set the day of month to 1
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); //get day of week for 1st of month
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
//print month name and year
System.out.println(new SimpleDateFormat("MMMM YYYY").format(calendar.getTime()));
System.out.println(" S M T W T F S");
//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++) {
System.out.printf("%2d ", dayOfMonth);
dayOfMonth++;
}
System.out.println();
}
Output:
February 2014
S M T W T F S
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
Related
My code compiles and runs perfectly, but when I any dates that are Saturdays the output is 'null' instead of 'SATURDAY'. Examples will be provided below to further explain this problem.
I have tried to change my if statement on my "getDayOfWeek" method but I seem to have no solution, I have also tried to obtain help from an experienced coder but they seem to be struggling due to java not being their main language...
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 isDateValid() {
if (month > 12 || month < 1 || day < 1) { // if values exceed 12 or are negative: return false
return false;
} else if (year <= 1582 && month <= 10 && day <= 15) { // starting date
// checking
return false;
} // for 31 day months: January, March, May, July, August, October, December
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: April, June, September, November
else if (month == 4 || month == 6 || month == 9 || month == 11) {
if (day > 30) {
return false;
}
} // February check
else if (month == 2) {
// leap year check for February
// 29 days in a leap year
// 28 days in a common year
if (isLeapYear()) {
if (day > 29) {
return false;
}
} else {
if (day > 28) {
return false;
}
}
}
return true;
}
// checks if input 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;
}
}
// method returns the day of MyDate object
public int getDay() {
return day;
}
// parameter for day to set
public void setDay(int day) {
this.day = day;
}
// method returns the month of MyDate object
public int getMonth() {
return month;
}
// parameter for month
public void setMonth(int month) {
this.month = month;
}
// method returns the year of MyDate object
public int getYear() {
return year;
}
// parameter for year
public void setYear(int year) {
this.year = year;
}
// method returns all variables: day/month/year of MyDate object
public String toString() {
return day + "/" + month + "/" + year;
}
}
public class MyCalendar {
//enums for days of week
public static enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
};
//enums for month of year
public static enum Month {
JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER;
};
//enums for week number of month
public static enum Week {
FIRST, SECOND, THIRD, FOURTH, FIFTH;
};
//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 dateValid = false; //valid date false
Scanner input = new Scanner(System.in); //scanner for input
MyDate enteredDate = null;
//till valid date found
while (!dateValid) {
System.out.print("Enter the date as day month year : ");
//taking input and creating date output
enteredDate = new MyDate(input.nextInt(), input.nextInt(), input.nextInt());
//validating date input
if (enteredDate.isDateValid()) { //if valid
MyCalendar myCalendar = new MyCalendar(enteredDate);
//creating calendar table
myCalendar.printDateInfo(); //printing date info
myCalendar.printCalendar(); //printing calendar
dateValid = true; //setting validate to true
} else {
System.out.println(enteredDate + " is not a valid date, please re-input 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 input month
public void printCalendar() {
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("Su Mo Tu We Th Fr Sa");
// The order of days depends on the input of date
// to display output of calendar
for (int day = 0; Day.values()[day] != firstWeekdayOfMonth; day++) {
System.out.print(" "); // this loop to print the first day in the
// 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
*
* Zellar's congruence to calculate the day of week
* for any given date after October 15 1582
* (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;
}
}
Expected results:
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
Actual results:
25/05/2019 is a null 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
Results of another date (that is not a Saturday):
24/05/2019 is a FRIDAY 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
Specified problem:
The output prints null on all dates that are on the day of Saturday, whereas other dates that are not a Saturday will achieve the correct output needed.
if (h < Day.values().length && h > 0) {
should change to
if (h < (Day.values().length + 1) && h > 0) {
If this is for production code, the comment by Basil Bourque is correct: you should not develop your own MyDate class but rely on the built in LocalDate class.
If on the other hand, as I would assume, this is a programming exercise, it’s a fine one, and there’s no reason (that I can see) why you shouldn’t struggle your way through it.
Your formula for calculating the day of the week is:
//calculating h value
int h = (q + (13 * (m + 1) / 5) + K + (K / 4) + (J / 4) + 5 * J) % 7;
(As an aside, please find better variable names and also respect the Java naming convention: a variable name cannot be an uppercase letter.) I don’t understand the formula, but assuming that it is correct, it calculates the day of week as 0 = Saturday, 1 = Sunday up to 6 = Friday. To use this number as a lookup into your Day enum use
output = Day.values()[(h + 6) % 7]; //getting respective enum value
Since h will always be non-negative and less than 7, you don’t need the enclosing if statement. Just assign to output unconditionally. With these changes I get
Enter the date as day month year : 25 5 2019
25/5/2019 is a SATURDAY located in the FOURTH week of MAY 2019
The Calendar of MAY 2019 is :
Su Mo Tu We Th Fr Sa
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
I was trying to build a beginner calendar exercise project and all I want is if last date of January ends on Sunday then start next month from Monday. Here is my code;
public static void main(String[] args)
{
String[] months= {"January","Febuary","March","April","May","June"
,"July","August","september","October","November"
,"December"
};
String[] weekdays= {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
int x;
for(int k=0;k<12;k++)
{
if(months[k]=="April" ||months[k]=="june" ||months[k]=="September" ||months[k]=="November")
{x=30;}
else if(months[k]=="Febuary")
{x=28;}
else {x=31;}
System.out.print(months[k]+"\n");
for(int i=0;i<weekdays.length;i++)
{
System.out.print("\t"+weekdays[i]);
}System.out.println();
for(int m=1;m<=x;m++) {
if(((m-1) %7) == 0) //line break after 7 characters
{
System.out.println();
}
System.out.print("\t"+m);
}
System.out.println();
}
}
I think you use not correct approach. Working with dated relates to working with Locale, because all these names like name for the month, weekdays in different format are already in the JVM. You should use it:
public static void printCalendar(LocalDate date, Locale locale) {
DateFormatSymbols symbols = new DateFormatSymbols(locale);
WeekFields weekFields = WeekFields.of(locale);
printMonthName(symbols, date);
printWeekdayNames(symbols, weekFields);
printWeekdays(weekFields, date);
}
private static void printMonthName(DateFormatSymbols symbols, LocalDate date) {
System.out.println(symbols.getMonths()[date.getMonthValue() - 1]);
}
private static void printWeekdayNames(DateFormatSymbols symbols, WeekFields weekFields) {
String[] weekdays = symbols.getShortWeekdays();
DayOfWeek firstDayOfWeek = weekFields.getFirstDayOfWeek();
int offs = firstDayOfWeek == DayOfWeek.SUNDAY ? 1 : firstDayOfWeek.ordinal() + 2;
for (int i = 0; i < 7; i++)
System.out.print('\t' + (offs + i >= weekdays.length ? weekdays[(offs + i) % 7] : weekdays[offs + i]));
System.out.println();
}
private static void printWeekdays(WeekFields weekFields, LocalDate date) {
LocalDate cur = date.withDayOfMonth(1).with(weekFields.dayOfWeek(), 1);
boolean stop = false;
do {
if (cur.getMonthValue() == date.getMonthValue())
System.out.format("\t%2d", cur.getDayOfMonth());
else
System.out.format("\t ");
cur = cur.plusDays(1);
if (cur.getDayOfWeek() == weekFields.getFirstDayOfWeek()) {
System.out.println();
stop = cur.getMonthValue() != date.getMonthValue();
}
} while (!stop);
}
Test1:
printCalendar(LocalDate.of(2018, Month.DECEMBER, 17), Locale.US);
December
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
Test2:
printCalendar(LocalDate.of(2018, Month.DECEMBER, 17), Locale.ITALIAN);
dicembre
lun mar mer gio ven sab dom
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
Your program still needs some adjustments:
1. The first day of the year can be sunday or other day of the week.
2. If the last day of the of the month is sunday, you should continue the order and not starting with sunday from the beginning.
I will propose you to adjust you current code, or you can use an existing library https://www.javatpoint.com/java-util-calendar.
I have written a program that is taking input from the user stating the year and the month, and am trying to print out the month. I can get the month to print and my spacing is working. However, I cannot get the days to work. The first day of the month is right for January 2018, but it isn't right when I do it for a different year or later month. I have to use the java package calendar. I have printed my code below is there something wrong with my code? Is there any way to fix it?
import java.util.Calendar;
import.java.util.Scanner;
public class MonthCalendar {
public static void main(String[] args) {
int year; // year
int startDayOfMonth;
int spaces;
int month;
//Creates a new Scanner
Scanner scan = new Scanner(System.in);
//Prompts user to enter year
System.out.println("Enter a year: ");
year = scan.nextInt();
//Prompts user to enter month
System.out.println("Enter the number of the month: ");
month = scan.nextInt();
//Calculates the 1st day of that month
Calendar cal = Calendar.getInstance();
cal.set(year, month - 1, 1);
int day = cal.get(Calendar.DAY_OF_WEEK) - 1;
// months[i] = name of month i
String[] months = {
" ",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
// days[i] = number of days in month i
int[] days = {
0,
31,
28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
};
// check for leap year
if ((((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) && month == 2)
days[month] = 29;
// print calendar header
// Display the month and year
System.out.println(" " + months[month] + " " + year);
// Display the lines
System.out.println("___________________________________________");
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
// spaces required
spaces = (days[month + 1] + day) % 7;
// print the calendar
for (int i = 0; i < spaces; i++)
System.out.print(" ");
for (int i = 1; i <= days[month]; i++) {
System.out.printf(" %4d ", i);
if (((i + spaces) % 7 == 0) || (i == days[month])) System.out.println();
}
System.out.println();
}
As pointed out in the comments already your problem is not in the date calculation itself but in the way you set the spaces initially:
spaces = (days[month+1] + day )%7;
That should instead be:
spaces = day;
You only need to know the weekday you're at, to know how far you must move in the first week regarding spaces. So if you are in a Sunday you advance 0 spaces, but if you are on Tuesday you want do advance 2 spaces, and so on and so forth. In the end you advance as many spaces as your starting weekday, which is what the day variable holds.
Take a look at the code giving the proper output for February 2018 in Ideone
Which yields the following output:
Enter a year:
2018
Enter the number of the month:
2
February 2018
___________________________________________
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
So basicaly, everything works like it should. But the main thing that should be correct, which is the date, is wrong, so far for october 2015 it is correct but for some reason i cannot detect, the other months i have tried so far are incorrect when compared to the calendar in my computer.
Here is my program, maybe you have some valid input to help me with these issues.
public static boolean isLeapYear(int year) {
int month = 0;
int s = getDaysIn(month, year);
return year % 4 == 0 && (year % 100 != 0) || (year % 400 == 0);
}
public static int getDaysIn(int month, int year) {
switch (month) {
case 1:
return 31;
case 2:
if (isLeapYear(month)) {
return 29;
} else {
return 28;
}
case 3:
return 31;
case 4:
return 30;
case 5:
return 31;
case 6:
return 30;
case 7:
return 31;
case 8:
return 31;
case 9:
return 30;
case 10:
return 31;
case 11:
return 30;
case 12:
return 31;
default:
return -1;
}
}
public static String getMonthName(int month) {
switch (month) {
case 1:
return "January";
case 2:
return "February";
case 3:
return "March";
case 4:
return "April";
case 5:
return "May";
case 6:
return "June";
case 7:
return "July";
case 8:
return "August";
case 9:
return "September";
case 10:
return "October";
case 11:
return "November";
case 12:
return "December";
default:
return "Invalid month.";
}
}
public static int getStartDay(int month, int year) {
int days = 0;
for (int i = 1900; i < year; i++) {
days = days + 365;
if (isLeapYear(i)) {
days = days + 1;
}
}
for (int i = 1; i < month; i++) {
days = days + getDaysIn(month, year);
}
int startday = (days + 1) % 7 + 2;
return startday;
}
public static void displayCalendar(int month, int year) {
String monthName = getMonthName(month);
int startDay = getStartDay(month, year);
int monthDays = getDaysIn(month, year);
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
int weekDay = startDay - 1;
for (int i = 1; i < startDay; i = i + 1) {
System.out.print(" ");
}
for (int x = 1; x <= monthDays; x++) {
weekDay = weekDay + 1;
if (weekDay > 7) {
System.out.println();
weekDay = 1;
}
System.out.format(" %3d", x);
}
if (weekDay > 7) {
System.out.println();
}
}
Your getStartDay is actually where your error lays :
for (int i = 1; i < month; i++) {
days = days + getDaysIn(month, year);
}
int startday = (days + 1) % 7 + 2;
return startday;
Should be replaced with :
for (int i = 1; i < month; i++) {
days = days + getDaysIn(i, year);
}
int startday = (days % 7) + 2;
return startday;
There is a minor problem with your loop as you see.
You should have had used your incrementor i in your getDaysIn calls to count the days from the begin of the year until the month you want to display.
Second error is here :
int startday = (days + 1) % 7 + 2;
The logic behind this expression is still a mystery for me.
Let's break this off with a concrete example :
Let's say we want to display FEB 1900. Easy to do because we start at the begin of JAN 1900 so we can count the days easily (31 days in january so days = 31)
Which result will the first expression return?
= (31 + 1) % 7 + 2
= 32 % 7 + 2
= 4 + 2
= 6
Because day 1 in your logic is SUNDAY, day 6 is FRIDAY.
Let's check it out :
Not really the expected result right?
I see one more problem with this method.
Let's imagine days = 33 (this will never happens but we need this example here).
= (33 + 1) % 7 + 2
= 34 % 7 + 2
= 6 + 2
= 8
What would the 8th day of the week be?
The explanation of the correct answer is the following :
(days % 7) + 2
days % 7 gives us the value of the last day of the following month when weeks begin with MONDAY.
To this value, we add 2 :
1 to have the beginning day of the wanted month.
1 because our calendar begins with sunday and we'll have to slide our days on the calendar view.
Here is the full code (that I also modified a bit to make it more compact) :
public class Calendar{
public static void main(String[] args) {
// INSERT YOUR TESTS HERE
}
public static boolean isLeapYear(int year) {
return year % 4 == 0 && (year % 100 != 0) || (year % 400 == 0);
}
public static int getDaysIn(int month, int year) {
switch (month) {
case 1 : case 3 : case 5 : case 7 : case 8 : case 10 : case 12 :
return 31;
case 4 : case 6 : case 9 : case 11 :
return 30;
case 2:
return isLeapYear(year) ? 29 : 28;
default:
return -1;
}
}
public static String getMonthName(int month) {
String[] months = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
return month <= 12 && month > 0 ? months[month - 1] : "Invalid month";
}
public static int getStartDay(int month, int year) {
int days = 0;
for (int i = 1900; i < year; i++) {
days += 365;
if (isLeapYear(i)) {
days = days + 1;
}
}
for (int i = 1; i < month; i++) {
days = days + getDaysIn(i, year);
}
int startday = (days % 7) + 2;
return startday;
}
public static void displayCalendar(int month, int year) {
String monthName = getMonthName(month);
int startDay = getStartDay(month, year);
int monthDays = getDaysIn(month, year);
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
int weekDay = startDay - 1;
for (int i = 1; i < startDay; i = i + 1) {
System.out.print(" ");
}
for (int x = 1; x <= monthDays; x++) {
weekDay = weekDay + 1;
if (weekDay > 7) {
System.out.println();
weekDay = 1;
}
System.out.format(" %3d", x);
}
if (weekDay > 7) {
System.out.println();
}
}
}
EDIT
You should try to write something in your main method if nothing displays.
public static void main(String[] args) {
for (int i = 0 ; i < 5 ; i++){
System.out.println(getMonthName(i+1) + " " + (2010 + i));
displayCalendar(i+1, 2010 + i);
System.out.println();
}
}
Gives the following output :
January 2010
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
February 2011
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
March 2012
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
April 2013
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
May 2014
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
and thanks for reading me.
I have a little problem that is that I need to Know the first/last day of a week in a month and a year, so:
public String getFirstDayOfWeekAndMonth(int year, int month, int week){
Calendar weekCalendar = Calendar.getInstance();
weekCalendar.clear();
weekCalendar.set( Calendar.YEAR, year );
weekCalendar.set( Calendar.MONTH, month-1); // zero-based
weekCalendar.set( Calendar.WEEK_OF_YEAR, week );
return... ?
}
For example for the next calendar:
Month Week M T W T F S S FirstDay LastDay
1 1 2 3 4 5 1 5
2 6 7 8 9 10 11 12 6 12
1 3 13 14 15 16 17 18 19 13 19
4 20 21 22 23 24 25 26 20 26
5 27 28 29 30 27 30
5 1 2 3 1 3
6 4 5 6 7 8 9 10 4 10
2 7 11 12 13 14 15 16 17 11 17
8 18 19 20 21 22 23 24 18 24
9 25 26 27 28 25 28
9 1 2 3 1 3
3 10 4 5 6 7 8 9 10 4 10
...
I have problems with the weeks that are in 2 months (on example 5 and 9). Could you help me please?
Thank You very much.
I recommend using the brilliant Joda-Time library for all your timing needs (which I also recommend to make a standard import in all you projects).
With that, a (not very clean, yet working) solution would be this:
public String getFirstDayOfWeekAndMonth(int year, int month, int week) {
DateTime firstDayOfMonth = new DateTime(year, month, 1, 0, 0, 0, 1);
DateTime lastDayOfMonth = new DateTime(year, month, firstDayOfMonth.dayOfMonth().getMaximumValueOverall(), 0, 0, 0, 1);
// european style (MON - SUN)
DateTime firstOfWeek = new DateTime(year, 1, 1, 0, 0, 0, 1).plusWeeks(week - 1).withDayOfWeek(1);
DateTime lastOfWeek = firstOfWeek.withDayOfWeek(7);
int firstDay;
int lastDay;
if(firstOfWeek.isBefore(firstDayOfMonth))
firstDay = firstDayOfMonth.getDayOfMonth();
else
firstDay = firstOfWeek.getDayOfMonth();
if(lastOfWeek.isAfter(lastDayOfMonth))
lastDay = lastDayOfMonth.getDayOfMonth();
else
lastDay = lastOfWeek.getDayOfMonth();
String returner = String.format("%d - %d", firstDay, lastDay);
return returner;
}
I don't quite get why you would want to return a String from your method, but I guess you have a reason. I just assumed a format, you can of course change it if you want.
Maybe a simple logical test?
For first day of the week:
If (resultDate.month < input.month){
resultDate = firstDayOf(input.month);
}
and for the last day of the week
If (resultDate.month > input.month){
resultDate = lastDayOf(input.month);
}
Well, I have develop a method that returns the first and the last day, wothin any other library:
private static int getFirstDayOfWeek(int year,int month,int week){
return getFirstLastDayOfWeek(true,year,month,week);
}
private static int getLastDayOfWeek(int year,int month,int week){
return getFirstLastDayOfWeek(false,year,month,week);
}
private static int getFirstLastDayOfWeek(boolean first, int year,int month,int week){
int exit = 0;
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month-1);
if (!first)
calendar.add(Calendar.DAY_OF_MONTH, 6);
// 1st day of the week
Date date = calendar.getTime();
// The month and the day of the 1st day of the week
int theMonth = Integer.valueOf( getInstance().getStrDate(date,"MM") );
if (theMonth!=month)
exit = (first?1:new GregorianCalendar(year, month-1, 1).getActualMaximum(Calendar.DAY_OF_MONTH));
else
exit = Integer.valueOf( getInstance().getStrDate(date,"d") );
return exit;
}