I'm trying to setup my addToDay function. I'm currently stuck on how to proceed with this or even write it correctly. The function itself will take a variable that ranges from -100 to 100. So you would basically add that variable to the current and if it was below the 0 then subtract a month or if it was above the months max day then add a month. Which i have that function setup so all i would have to do is call addToMonth with the correct amount. My problem lies within the amount of days each month has. For example, October has 31 days while November has 30. I have a function that will return the number of days in the current set month so i can call that to get how many max days should be in the current month. I'm thinking maybe a while loop would work but i just wanted to get anyone's thoughts on the best way to set it up.
I have 3 private ints: month, day, year. These are what need to be changed. I have both addTo functions for month and year setup already.
Here are some other functions i have created that can be used in this:
1. addToMonth(int delta) - changes the current month depending on the given parameter
2. getDaysInMonth() - will return the days in a month depending on the month itself
3. validateDay() - Will return true or false if the days fall outside the wanted requirements.
I don't want to use the calendar utility
I also don't want to use any other utilities. Just the base code with Junit for testing
Joda's plusDays() function and Java 8 LocalDate already has the logic that you are trying to achieve
Alright so i ended up just copying my original addToMonth function and modifying it abit to fit with days. So far it works but i do think it'll fail in the cases of different amounth of days not lining up.
Related
This exercise is from Java MOOC 92.3
Simply, I have two dates.
And a method which gives me the difference of the two.
(for instance: 3/10/2011 and 3/9/2012)
My method states that as long as the month and the day are greater than the later, then simply subtract the one for which the method is called.
Here's the problem:
If a date given as a parameter has a greater year, then when I subtract the two I come out with a negative number (ex: 2011 - 2012).
public int differenceInYears(MyDate comparedDate){
int result = 0;
if(this.month >= comparedDate.month && this.day >= comparedDate.day){
result = this.year - comparedDate.year;
}else{
result = this.year - comparedDate.year;
result--;
}
return result;
The code beyond the else is for the case in which the year is not what it may look to be (Example: If I was born in May 2000 and I technically should be 20 since it is 2020, but since it is not May yet, I am therefore 19).
My conditions are still met within the first if statement, even though the result is not correct. I have tried finding a case where I can appease both cases where it does not matter what date goes first, but I am struggling with the logic. Would appreciate input.
First, if I understand correctly that this is an exercise, it’s a fine exercise. For production work one would never invent their own date class but would and should use LocalDate from the standard library for a date. And ChronoUnit.YEARS.between() for finding your age.
If you have not yet had your birthday this year, you want to subtract one year from the result. This is correct. So how do we determine whether this year’s birthday is in the future? Take a look at the following possibilities. I have not run your code, so have filled out the last column from what I think will happen from reading the code.
Today Birthday Subtract 1? Does your code subtract 1?
--------------------------------------------------------
Apr 3 Feb 1 No No
Apr 3 Feb 6 No Yes
Apr 3 Apr 1 No No
Apr 3 Apr 6 Yes Yes
Apr 3 May 1 Yes Yes
Apr 3 May 6 Yes Yes
Another way to put the question: if the months are different, do we need to compare the day of month too?
I like your attitude. In accordance with your title I am not giving away the correctly working code. I too am convinced that you will not only learn more from writing it yourself, it will also give you greater pleasure. If you’re still stuck, please leave a comment and I’ll take one more look.
EDIT: For the problem of getting a negative result if the dates are in the opposite order: The simplest solution is to check the result after you’ve calculated. If it is negative, redo the entire calculation with the dates reversed. That is, with this. and comparedDate. in each other’s places. One elegent option is that in this case you tell the other MyDate object to do the calculation instead. Call the differenceInYears method of the other object passing this as argument.
I have a date supplied by the user and of course today's date.
I'm attempting to verify that the difference between the 2 days is at least 2 weeks. I've done this using standard libraries - but I'm attempting to do this using jodaTime and I'm having some difficulty.
// BAD CODE - doesn't work
// NOTE: getUserSuppliedDate() returns an instance of java.sql.Date
// Also assume that validation prior to this call has been run that
// validates that the userSuppliedDate comes AFTER today's date - not sure if
// that is relevant in the context I'm attempting to use these particular jodaTime APIs.
DateTime jodaStartDate = new DateTime(getUserSuppliedDate());
if (Days.daysBetween(jodaStartDate, DateTime.now()).isLessThan(Days.days(14))) {
System.out.println("Bad user. You have chosen...poorly.");
}
else {
System.out.println("Well done user. You have supplied wisely.");
}
// GOOD CODE ---- ? Help =)
Your code gives you the wrong result because the dates supplied to Days.daysBetween() are in the wrong order. Since you specified that the user supplied date comes after the current date, your approach will result in a negative number of days.
It will work correctly if you switch the order, putting the earliest date first.
Compare the following two:
DateTime jodaStartDate = new DateTime().withYear(2018)
.withMonthOfYear(7)
.withDayOfMonth(5); // 15 days from now
System.out.println(Days.daysBetween(jodaStartDate, DateTime.now())); // "P-15D"
System.out.println(Days.daysBetween(DateTime.now(), jodaStartDate)); // "P15D"
In the first case, -15 days will evaluate to less than 14 days.
Using weeks instead of days, you'd run into the same problem:
System.out.println(Weeks.weeksBetween(jodaStartDate, DateTime.now())); // "P-2W"
System.out.println(Weeks.weeksBetween(DateTime.now(), jodaStartDate)); // "P2W"
This is my table
Sample(tablename)
-Day_start(column1)
-Day_end(column2)
-Total_days(column3)
-Days_left(column4)
Day_start(column1)
-March 1 2017(data)
Day_end(column2)
-April 5 2017(data)
Total_days(column3)
-36 (data)
days_left(column4)
-36(data)
Sorry for my last question, im not good in English!.. So this is my question In the day of March 2 2017 the days left must be 35. so everyday the days_left will decrease automatically I only know the code of between two dates whichis my total_days. But I dont know how to decrease it by 1 automatically per day . Then it will diplay in the table of netbeans
well you can store the current date somewhere in a file. then when the program runs again you can compare the date from the file with the current data, finally create a function to find the diffrence in days since the program was last opened. you can als just print the date it was last opened.
I have this assignment due by the end of the month and I'm already halfway done. We had to use Zeller's congruence to calculate the day of the week that the 1st landed on. From that point (and accounting for leap years), you have to print off a calendar of the corresponding year using loops. The teacher said that this should be a really short program and we should not try to brute force the the logic of the program (basically, don' t use a bunch of if else and loops for each month). I already have the math calculations and leap year part down, but I can't wrap my head around how to make this for loop work for numerous reasons:
How would I go about factoring in whitespaces for each month? Like how many nested loops will I actually need?
Would I need to write different loops for Leap years, months with 31 days, and months with 30 days, etc or can all this be handled with 1 giant nested loop?
For example, I just started off writing a for loop just to see if I could print off a typical 31 day calendar without any special formatting (whitespaces, Month name, days etc). Here was my first test at using a for loop:
for(int i = 1; i < 31; i++)
{
for(int j = 0; j < 7; j++)
{
System.out.print(i + "\t");
i++;
if(j == 6){
i--;}
if(i > 31)
{
break;
}
}
System.out.print("\n");
}
What is the logic behind using it for multiple months and whitespaces. I welcome all help, but please DO NOT GIVE ME SOURCE CODE. I want the satisfaction of getting this done with code I've written, and like I said, this is also an assignment and I won't really learn from copying and pasting code. Just throw me a bone about the logic I need to use. I can work in all other conditionals for special cases. Thanks guys.
Ok, you need to manage something which varies between a fixed set of values, so you basically need a way to access these variable data from within a loop.
The best tool to fullfil this problem is probably an array.
If you store inside an array, for example the duration of the months you will be able to access them in a straightforward way (through an index) so that you won't need any conditional chain, you will just need the index of the current month, eg monthDurations[i] == 31.
If you want to structure everything better you could define your own Month class or Day class or whatever you need to keep track of printing issues (eg white spaces or names) so that everything will be easily encapsulated and maintainable.
I would write a function to display one month with parameters: dayOfWeek, numberOfDays, [name, firstDayOfWeek]
dayOfWeek - what day of week is 1st day of the month
numberOfDays - number of days in this month
optional parameters You may implement if You like
name - name of the month
firstDayOfWeek - some calendars use Sundays other use Mondays as first day, if You like to have this flexibility You can implement this as well.
And the logic is simple You can do with just one loop that would iterate numberOfDays+dayOfWeek-1 times.
Inside You just need to check for end of week to make new lines and display empty spaces dayOfWeek-1 times in first week.
I came across the XMLGregorianCalendar class a while ago and I was impressed by the way it made GregorianCalendar look lightweight. ;)
Recently, I noticed a method BitInteger getEon() which baffles me.
From the Javadoc for XMLGregorianCalendar
getYear() is a value between -(10^9-1) to (10^9)-1 or DatatypeConstants.FIELD_UNDEFINED.
getEon() is high order year value in billion of years.
It occurs to me that as the length of day on Earth changes significantly over the millions of year and there for the number of days in a year has changed. The Gregorian calendar wouldn't make sense a billion years ago or a billion years hence. So getEon() can only be sensibly set to 0 or left undefined which has much the same outcome.
My question: Am I missing something? Is there a sensible use for the getEon() method?
Well, according to http://www.merlyn.demon.co.uk/critdate.htm the unix time using 64 bits integer will end around the year 3E11. Given that Java uses milliseconds instead of seconds, Java time (64 bits) will end around 3E8. So this provides some expansion beyond the limits of the JVM.
In a more practical note, when you use this scale of time you are talking about geological, evolutionary or cosmological events, so the rest of the data in a date (year, month, day...) is meaningless. It is better if you use a long with the year (or even an int with the eon) and forget about the rest of it.
It looks like somebody was really, really bored (and boring).
Edit: Of course, there is always some crazy problems that can use it, but not real world problems (as in: "if we have a Hanoi Towers with 64 discs and move a disc a second, when would we finish swapping the towers").