i use java 8 LocalDate and Period classes to add and remove years, months and days. Why in some cases if add Period to date and remove the same period java 8 return another date?
LocalDate date = LocalDate.of(2023, 1, 30);
Period period = Period.of(6, 1, 1);
System.out.println(date.plus(period).minus(period));
why the result is 2023-01-31 not 2023-01-30
Why in some cases if add Period to date and remove the sane period java 8 return another date?
Because that's how calendrical arithmetic works - months are uneven lengths, and it makes things tricky to say the least.
You're adding "six years, one month, one day" to January 30th 2023. What do you expect the result of that to be? There are potentially multiple different options... logically it sounds like you mean "February 31st 2029" which doesn't exist... so the API rolls it over to March 1st 2029.
Now subtracting six years, one month and one day from March 1st 2029 is also somewhat ambiguous, but it sounds reasonable to make it January 31st 2023 - if you subtract 6 years to get to March 1st 2023, then 1 month to get to February 1st 2023, then 1 day you get to January 31st.
Fundamentally: don't expect calendrical arithmetic to behave like regular maths. It just doesn't work that way.
Related
I am looking to build up a function that return an array with all week numbers of the previous months in a year that are the same week number of one particular month.
I am using as first day of week Monday and I am taking as first week of month week with the first Monday of current month.
Input: week of year and year. For example, 27 and 2019. The first week of July (7).
Output: array of week of months. For example, [2, 6, 10, 14, 19, 23, 27].
What I try:
private void getResult(int weekYear)
{
LocalDate date = LocalDate.now();
final int weekNumber = 27;
LocalDate newDate = date.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber);
int month = newDate.getMonthValue();;
int weekMonth = LocalDate.from(newDate).get(WeekFields.ISO.weekOfMonth());
System.out.println(newDate);
System.out.println(month);
System.out.println(weekMonth);
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= month; i++)
{
LocalDate tempDate = date.withYear(2019).withMonth(i).with(WeekFields.ISO.weekOfMonth(), weekMonth);
int tempYear = LocalDate.from(tempDate).get(WeekFields.ISO.weekOfWeekBasedYear());
list.add(tempYear);
}
list.forEach((e) -> System.out.print(e + " "));
}
int weekYear = 27;
getResult(weekYear);
What I get: [1 6 10 14 18 23 27].
What I am looking for: I have two question:
First one: the results obtained are different from those expected. I think the problem is due to the fact that I didn't specify how to calculate the first week of the month (first Monday of the month). Is it right? How can I solve that?
Second one: What is a better solution?
The key here is understanding a few points:
You are numbering weeks in two different ways. For the week of year you are using ISO numbering: the first week of the year is the one that includes at least 4 days of the new year. For week of month you are counting the Mondays (you may say that the first week of the month is the one that includes seven days of the month, not four).
The week number may not always exist. If your starting point is in 0th or the 5th week of the month, a preceding month may not have that week in it.
the results obtained are different from those expected. I think the
problem is due to the fact that I didn't specify how to calculate the
first week of the month (first Monday of the month). Is it right? How
can I solve that?
You are correct. To count the Mondays of the month you may use:
LocalDate tempDate = date.withYear(2019)
.withMonth(i)
.with(ChronoField.DAY_OF_WEEK, DayOfWeek.MONDAY.getValue())
.with(ChronoField.ALIGNED_WEEK_OF_MONTH, weekMonth);
(DayOfWeek.MONDAY.getValue() is just of wordy way of saying 1, of course, but conveys the intention better, so I prefer it.)
With this change to your code the output is the expected:
2 6 10 14 19 23 27
The key is ChronoField.ALIGNED_WEEK_OF_MONTH. The aligned weeks of a month start from the 1st of the month and are always 7 days regardless of the days of the week. The first aligned week is from the 1st through the 7th of the month, the 2nd aligned week if from 8th through 14th, etc. Since we have set the day of week to Monday, setting the aligned week to 1 gives us the 1st Monday of the month, etc.
We’re not done yet. If I set weekNumber to 40, I get:
2 6 10 14 14 23 27 27 36 41
I had expected 40 to be the last number in the list, but it is not there. Week 40 of 2019 is from Monday September 30 through October 6, so if I understand correctly you want the 5th week of those months that have a 5th week. This brings us back to the issue of not all month having a week 5 (because they don’t have 5 Mondays). What happened was that since I ran your code on a Tuesday, it took Tuesday in week 40, which is October 1, as a starting point, and therefore gave me the 1st rather than the 5th week of every month.
are there better solutions? Can you suggest one?
I can’t really. What you’ve got is fine.
Only you’re not using the int weekYear parameter. You may want to use it in place of your weekNumber local variable. In any case you should delete one of them and use the other.
And this unrelated tip: Your use of LocalDate.from(someLocalDate) is redundant since it just gives you the same LocalDate again (either the same object or an equal one, I don’t know or care). Just use someLocalDate in those situations.
When using java.time in Scala I experienced a strange behavior. I want to calculate the number of months between two dates like this:
import java.time._
Period.between(LocalDate.parse("2015-03-31"), LocalDate.parse("2015-04-30"))
// java.time.Period = P30D
// I would expect java.time.Period = P1M
Period.between(LocalDate.parse("2015-03-31"), LocalDate.parse("2015-05-01"))
// java.time.Period = P1M1D
Is this a bug or do I have got it all wrong?
org.joda.time works as I would expect it:
import org.joda.time.DateTime
import org.joda.time.Months
Months.monthsBetween( new DateTime().withDate(2015, 3, 31), new DateTime().withDate(2015, 4, 30))
//org.joda.time.Months = P1M
When adding months to a java.time.LocalDate it works fine:
java.time.LocalDate.parse("2015-03-31").plusMonths(1)
// java.time.LocalDate = 2015-04-30
This is not a bug, and it is behaving like expected (see also JDK-8152384 and JDK-8037392, which were closed as "Not An Issue"). Joda Time and the Java Time API have different behaviour regarding this. Quoting Stephen Colebourne from the previous bug report:
The OP appears to want a rule where the days are calculated based on the original month length, not the one that results once the month-year difference is applied. The OP is not wrong, its just that its not how we choose to make the calculation in java.time.
Indeed, from Period.between:
The period is calculated by removing complete months, then calculating the remaining number of days, adjusting to ensure that both have the same sign. [...] A month is considered to be complete if the end day-of-month is greater than or equal to the start day-of-month.
Between the 31st of March, and the 30th of April, no complete month has elapsed. As such, you have a period containing the number of days between the two dates, which is 30. To have the complete month of April elapsed, you need to add one day to the end date, and make it the 1st of June.
Joda has a different way of calculating the month period. From Months.monthsBetween:
This method calculates by adding months to the start date until the result is past the end date. As such, a period from the end of a "long" month to the end of a "short" month is counted as a whole month.
Joda explicitly takes the variable number of days in a month into account when calculating the number of months between the two dates. Java Time doesn't.
I agree that it is a bit unexpected, but it is the correct result if you take into account the javadoc.
From the javadoc
The start date is included, but the end date is not. The period is calculated by removing complete months, then calculating the remaining number of days, adjusting to ensure that both have the same sign. The number of months is then split into years and months based on a 12 month year. A month is considered if the end day-of-month is greater than or equal to the start day-of-month. For example, from 2010-01-15 to 2011-03-18 is one year, two months and three days.
The difference comes from what a "complete month" means.
In this case 1st April to 1st May (exclusive) is considered a complete month while 31st March to 30th April (exclusive) is not.
I believe the Period.between is returning P30D in the first example because the second parameter is exclusive. This is according to https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#between-java.time.LocalDate-java.time.LocalDate-
public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive)
I am writing my stubs in StubbyDB. And asserting the data in functional tests. This is something I am doing in my functional tests to calculate date for assertion (using joda datetime library)
DateTime now = DateTime.now();
DateTime future = now.plusMonths(6);
And this is something I am doing in my stubs;
{{TODAY+6m}}
But I am getting the difference of few days. Is this the bug or am I doing something wrong?
Edit
Consider today is "30 Sept 2016", and I add 5 months to it then
now.plusMonths(5) => 2017-02-28
{{TODAY+5m}} => 2017-03-02
Reason
As per joda-time documentation,
2007-03-31 plus one month cannot result in 2007-04-31, so the day of
month is adjusted to 2007-04-30.
However StubbyDB use javascript based date calculation which adjust date 2007-04-31 to 2007-05-01.
So this is not the bug but this is how these APIs work.
Solution
Found in sample application
use {{JODA_TODAY+6m}} instead of {{TODAY+6m}}
if you start with 30/09/2016 and add five months you get 30/02/2017.
But February only has 28 days.
It looks like Jodatime has "rounded down" to give you the maximum valid date for the month (i.e 28th Feb) whereas the other library/code is treating "30th Feb" as 2nd March (since that is technically two days past the 28th, which the 30th would also be).
Both are valid assumptions for handling dates IMHO and are a good lesson in why date handling is hard. You'll need to be explicit about which convention you want to follow and you may have to code your assertions to follow Jodatime's conventions.
See: DateTime::plusMonths(int)
Returns a copy of this datetime plus the specified number of months.
The calculation will do its best to only change the month field
retaining the same day of month. However, in certain circumstances, it
may be necessary to alter smaller fields. For example, 2007-03-31 plus
one month cannot result in 2007-04-31, so the day of month is adjusted
to 2007-04-30.
So, 30 Sept 2016 + 5 months = 28 Feb 2017 (according to Joda's logic) and it is not a bug
Here is sample code for adding months to given calendar date
public class Demo {
// create a calendar
Calendar cal = Calendar.getInstance()
// print current date
System.out.println("The current date is : " + cal.getTime());
// add 1 months from the calendar
cal.add(Calendar.MONTH, 1);
}
FYR How to add one month to a date and get the same day
I am trying to determine the sequential ordinal number of a weekday in a month in Java. i.e. if a Friday is the first or 3rd friday of a month.
I can not find a simple way after reading all the things I can find on Java Calendar and posts here. One way I can think of is to determine how many days the first week of this month have in this month and then adjust week_of_month based on what day the day in question is. However, it requires a little complicated calculation. Anyone knows a simple solution?
Just take the day of month, subtract 1, divide by 7, then add 1. The first seven days of the month are always the first (Tuesday, Wednesday, ...) whatever day of the week the actual 1st of the month is.
Personally I'd use Joda Time:
public int getWeekOfWeekDay(LocalDate date) {
return ((date.getDayOfMonth() - 1) / 7) + 1;
}
... but you could do the same using Calendar and fetching the value of the Calendar.DAY_OF_MONTH field.
EDIT: Actually, I've just noticed that for a change, java.util.Calendar is actually simpler than Joda Time - there's a particular field for it! All you need is:
int weekOfWeekDay = calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH);
From the docs for DAY_OF_WEEK_IN_MONTH:
Field number for get and set indicating the ordinal number of the day of the week within the current month. Together with the DAY_OF_WEEK field, this uniquely specifies a day within a month. Unlike WEEK_OF_MONTH and WEEK_OF_YEAR, this field's value does not depend on getFirstDayOfWeek() or getMinimalDaysInFirstWeek(). DAY_OF_MONTH 1 through 7 always correspond to DAY_OF_WEEK_IN_MONTH 1; 8 through 14 correspond to DAY_OF_WEEK_IN_MONTH 2, and so on.
I think I'd probably still use the Joda Time version because it's just a much nicer API all round, but if you're forced to use Calendar, at least you can do this in one shot.
I have maths problem ... (at the moment i solved it using manual iteration which is pretty slow) ...
For example if an employee got paid weekly (it can be fortnightly / every 2 weeks and monthly) with certain date (let's call the employee got paid every tuesday and for monthly the employee paid on certain date).
I have date range between 10th August 2009- 31 December 2009, now how to get frequency the employee got paid ?
is it possible to calculate this using jodatime ?
Example to make this question clear:
I have date range between Friday 14 August - Monday 14 Sept 2009 (31 days)
the employee got paid on every Tuesday
so he got paid on 18 & 25 August, 1 & 8 August we got 4 times payment
(frequency)
another example:
with the same date range Friday 14 August - Monday 14 Sept 2009 (31 days)
but different pay date .. for example on Sunday
so he got paid on : 15, 22 & 29 August , 5 & 12 September ... we got 5 times payment.
same date range but different pay day .. will result different.
So my question is, are there any formula to solve this case ?
at the moment I calculate using manual iterator .. which is very slow (because the range could be some years or months)
thank you
ps: I am using groovy .. any solutions using java or groovy or just algorithm are welcome :)
Oftentimes pay periods are on the 15th and the end of every month, so in that case you'd count the number of months and multiply by 2, checking the end conditions (if start is before the 15th, subtract one pay period; if end is after end of the month subtract one pay period).
It's possible to get counts of days, weeks, and months, but you'll have to add in the logic to handle the dodgy end conditions. It's probably not a simple formula, as the case I described demonstrates.
abosolutely, using the Weeks class is very simple:
DateTime start = new LocalDate(2009, 8, 10).toDateTimeAtStartOfDay();
DateTime end = new LocalDate(2009, 12, 31).toDateTimeAtStartOfDay();
int numberOfWeeks = Weeks.weeksBetween(start, end).getWeeks();
this code give 20 as result. It is right?
EDIT
maybe this is better:
DateMidnight start = new DateMidnight(2009, 8, 10);
DateMidnight end = new DateMidnight(2009, 12, 31);
int numberOfWeeks = Weeks.weeksBetween(start, end).getWeeks();
System.out.println(numberOfWeeks);
Subtracting one date from the other to get the "number of days" (or weeks) is generally the wrong way to go for these kinds of calculations. For example, if someone is 365 days old, they are exactly one year old, unless there was a February 29 during that time. In any (modern) 7-day period, there is always exactly one Tuesday; but for 8 days, it's either one or two. The calendar often figures into the calculations.
If they're paid once or twice a month, you do the easy calculation on the whole months -- starting on the first and ending on the last day of the month, which varies -- and then you have to consider partial months at the beginning and/or end. (Don't forget what happens if the 15th or last day of the month falls on a weekend.) If they're paid every one or two weeks, you can sync on a known payday, and then do the simpler math to figure the whole weeks before and/or since. (Don't forget holidays that fall on the payday.)
There are two tricks here: One is that the rules are different depending on the time frame. I mean, if a person is paid once a week, then in 7 days he gets paid once, in 14 days he gets paid twice, etc. But if a person is paid on the 1st and 16th of every month, I can't tell you how many times he was paid in 60 days without knowing what months were included: where they short months or long months?
The second is that you have to worry about the start and end of the time period. If a person is paid every Monday, then the number of times he gets paid in 8 days depends on whether the first day of the 8 is Monday.
Thus, I think you need to have different logic for schedules that are a fixed number of days and those that are tied to months or something else where the intervals can vary.
For the fixed number of days, the problem is fairly simple. The only complexity is if the time frame is not an exact multiple of the interval. So I'd say, find the first date in the interval on which a payday occurs. Then find the number of days between there and the end of the time period, divide by the interval and drop any fractions.
For example: A person is paid every Monday. How many pay days between March 1 and April 12? Find the first Monday in that range. Say it falls on March 4. Then calculate the number of days from March 4 to April 12. That would be 39. 39/7=5 and a fraction. Therefore he gets paid 5 more paychecks, for a total of 6.
For monthly pay, I think you'd have to separate out the first and last month. You could then count the number of months in the middle and multiply by the number of pays per month. Then for the first and last count how many are in them the hard way.
Just got solutions please check if I did something wrong
import org.joda.time.* ;
def start = new Date().parse("dd/MM/yy","14/08/2009");
def end = new Date().parse("dd/MM/yy","14/09/2009");
println("date range ${start} - ${end}");
def diff = end - start ;
println("diff : ${diff} days ");
println("how many weeks : ${diff/7}");
def payDay = 2 ; // Monday = 1 Sunday = 0
def startDay = new DateTime(start).dayOfWeek ; // 5 = Thursday
def startDayDiff = payDay - startDay ;
if(startDay > payDay){
startDayDiff = 7 + payDay - startDay ;
}
// for example if end on Friday (5) while Pay day is day 1 (Monday) then
// make sure end date is on Monday (same week )
// end date = end - ( endDay - payDay)
def endDay = new DateTime(end).dayOfWeek;
println("original end day: ${endDay}");
def endDayDiff = endDay - payDay ;
// otherwise ... if endDay < payDay (for example PayDay = Friday but End day is on Monday)
// end date = end - 7 + payDay
if(endDay < payDay){
endDayDiff = 7 - endDay - payDay ;
}
println("endDayDiff : ${endDayDiff}");
println("startDayDiff: ${startDayDiff}");
def startedOn = new DateTime(start).plusDays(startDayDiff);
println("started on : ${startedOn.toDate()}");
def endOn = new DateTime(end).minusDays(endDayDiff);
println("End on : ${endOn.toDate()}");
println("occurences : ${Weeks.weeksBetween(startedOn,endOn).getWeeks()+1}");
Tested using groovyConsole with Joda Time help .. :)