LocalDate wrong output with WeekFields [duplicate] - java

This question already has answers here:
Find start-end date of a week from week number
(4 answers)
How to get first day of a given week number in Java
(8 answers)
How to get dates of a week (I know week number)?
(7 answers)
How to get Date from Week Number, Year and dayOfWeek in java?
(3 answers)
Closed 1 year ago.
I need to get the first and the last day of a date composed by a year and a week. I tried this code:
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.Locale;
public class MyClass {
public static void main(String args[]) {
WeekFields weekFields = WeekFields.of(Locale.getDefault());
int year = 2021;
int week = 29;
// first day of the week
System.out.println(LocalDate.now()
.withYear(year)
.with(weekFields.weekOfYear(), week)
.with(weekFields.dayOfWeek(), 1));
// last day of the week
System.out.println(LocalDate.now()
.withYear(year)
.with(weekFields.weekOfYear(), week)
.with(weekFields.dayOfWeek(), 7));
}
}
My default Locale is it_IT and the output was correct, first day was 19/07/2021 and last day was 25/07/2021 (year week IT, format is dd/mm/yyyy).
I stopped the application and before running it I set the VM arguments -Duser.language=en -Duser.region=UK to test a different Locale but once run again the output was completely wrong.
For the week 29 of the year 2021 I expected the first day of the week to be 2021-07-19 and the last day 2021-07-25 (year week UK) but I instead got 2021-07-11 as the first day of the week and 2021-07-17 as the last day of the week.
What am I missing? Thank you.

Related

Why does DateTimeException only happens for the month of january [duplicate]

This question already has answers here:
SimpleDateFormat. format returning wrong date
(2 answers)
Convert java.util.Date to java.time.LocalDate
(14 answers)
Closed 9 months ago.
what does this error mean?
Exception in thread "AWT-EventQueue-0" java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 0
It only happens for the month of January
this is my line of code
public int computeAge(Date birthDay) throws ParseException {
LocalDate birthdate = LocalDate.of(birthDay.getYear(), birthDay.getMonth(), birthDay.getDay());
LocalDate curDate = LocalDate.now();
Period p = Period.between(birthdate, curDate);
return p.getYears();
}
This happens because Date uses month numbers from 0 to 11, but LocalDate uses month numbers from 1 to 12. So even if your program doesn't throw the DateTimeException, it won't give you the correct result.
Please stop using the Date class, and just use classes from the java.time package instead. Those particular methods - getDay(), getMonth() and getYear() were deprecated last century, if I recall correctly.
In this case, you should use LocalDate instead of Date, because it expresses a combination of year, month and day, with no time component.

How can i change year with LocalDate by adding weeks?

Here is my code. This method works only for 1 ( current year). When week number is more than 53, dates start from dates in first week in current year but not the next.
Year has 52 or 53 weeks, so when week is last (52or53) i have 2020-12-28 - 2021-01-03, but when I want get first week of next year (2021-01-04 - 2021-01-10) it outputs me first week from 2020 ( 2019-12-30 - 2020-01-05).
public void showPreviousNextWeekDays(DataBaseHelper dataBaseHelper, long weekChange) {
if (weekChange >= 0) {
LocalDate ld = LocalDate.now().plusWeeks(weekChange);
final long weekNumber = ld.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR); //takes week from current date
LocalDate firstDayOfWeek = ld.ofYearDay(ld.getYear(), (int)weekNumber)
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber)
.with(DayOfWeek.MONDAY);
LocalDate lastDayOfWeek = ld.ofYearDay(ld.getYear(), (int)weekNumber)
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber)
.with(DayOfWeek.SUNDAY);
String firstAndLastDayOfWeek = firstDayOfWeek.toString() + " - " + lastDayOfWeek.toString();
daysArrayAdapter = new ArrayAdapter<DayModel>(getActivity(), android.R.layout.simple_list_item_1, db.NextWeek(weekChange));
daysList.setAdapter(daysArrayAdapter);
How can i go forward with years also by adding weeks?
You are correct that your code is not correct. When I set weekChange to 14 and run today (September 29), I get 2019-12-30 - 2020-01-05 where expected result would be 2021-01-04 - 2020-01-10. Also for 15 and 16 weeks your code goes back to a week in the beginning of this year rather than finding a week in the beginning of next year as it should.
I suggest the following, which is also a bit simpler:
int weekChange = 14;
LocalDate ld = LocalDate.now(ZoneId.systemDefault()).plusWeeks(weekChange);
LocalDate firstDayOfWeek = ld.with(DayOfWeek.MONDAY);
LocalDate lastDayOfWeek = ld.with(DayOfWeek.SUNDAY);
String firstAndLastDayOfWeek = firstDayOfWeek.toString() + " - " + lastDayOfWeek.toString();
System.out.println(firstAndLastDayOfWeek);
Output when run today:
2021-01-04 - 2021-01-10
LocalDate uses the ISO calendar system including ISO weeks if not explicitly instructed otherwise. So we can be sure that ld.with(DayOfWeek.MONDAY) gives us Monday at the start of the same ISO week. Similarly ld.with(DayOfWeek.SUNDAY) gives us Sunday at the end of the ISO week. So there is nothing more to it.
What happened in your code?
Sticking to the case of weekChange 14 and running today.
ld becomes 2021-01-05 (Tuesday 14 weeks from now). This date is in week 1 of 2021, so weekNumber will be 1.
ofYearDay is a static method of LocalDate. So ld.ofYearDay(ld.getYear(), (int)weekNumber) gives you the same date as you would have got from LocalDate.ofYearDay(ld.getYear(), (int)weekNumber). It does not use ld for anything. Since weekNumber is 1, you get day 1 of 2021, so 2021-01-01. Passing the week number as the day of year to ofYearDay() is meaningless. 2021-01-01 happens to fall in week 53 of 2020. So with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber) adjusts the date back to week 1 of 2020. This is where we go a year wrong. The result is 2020-01-03. The Monday of that week is 2019-12-30, which explains why you got this as the first day of week in the output.
The last day of week is similar. And week numbers 2 and 3 are similar since you use the week number as a day of year, and January 2 and 3 fall in the last week of the previous year, 2020, too.
How did I find out? I ran your code in my debugger. There it was clear to see. If you haven’t yet learned to use a debugger. I suggest that now is the best of all times.

Why there is a difference between GregorianCalendar.getTimeInMillis() and GregorianCalendargetTimeInMillis(1970.01.01)) [duplicate]

This question already has answers here:
How do I calculate someone's age in Java?
(28 answers)
Why is January month 0 in Java Calendar?
(18 answers)
Closed 3 years ago.
I have tried to compare to Dates the Birthdate and the Current date
and then I tried to get the age.
But the Current date Funtion begins with another Date than the given date
My Code:
GregorianCalendar birthdate = new GregorianCalendar(2001,06,20);
long ms = System.currentTimeMillis() - birthdate.getTimeInMillis();
double years = (((double)ms / 1000)/31536000) ;
System.out.print(years);
// years Shoud be 18 here but it returns 17.3
if (years > 18) {
// Code Block
}
else{
System.out.print("to Jung");
}
Check the Constructor on GregorianCalendar.
public GregorianCalendar(int year,
int month,
int dayOfMonth)
Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
year - the value used to set the YEAR calendar field in the calendar.
month - the value used to set the MONTH calendar field in the calendar. Month value is 0-based. e.g., 0 for January.
dayOfMonth - the value used to set the DAY_OF_MONTH calendar field in the calendar.
You are creating a July 20th date, which is coincidentally offset by a single month, or approximately 0.08 years.
LocalDate birthdate = LocalDate.of(2001,06,20);
LocalDate currentdate = LocalDate.now();
int years = Period.between(birthdate , currentdate).getYears();
if (years >= 18) {
// Code
} else {
System.out.print("Sie sind zu Jung");
}
It Worked like this but I must change the hole code because everything was written with the GeorgianCalender.
I couldn't tell you why exactly your code, which should technically work, doesn't: there seems to be inaccuracies (leap days?) in the Calendar, or I'm missing something. Thanks to Compass, I know that I was missing something: months are 0-indexed in the constructor for Gregorian Calendar. 06 is July.
However, you shouldn't compare dates like this. If you don't want to use any other library, you can do this:
GregorianCalendar birthdate = new GregorianCalendar(2001,06,20);
GregorianCalendar today = new GregorianCalendar();
birthdate.add(Calendar.YEAR, 18);
System.out.print(birthdate.getTime().after(today.getTime()));

Is there a way to get starting date of a given weekNo of a given year Java? [duplicate]

This question already has answers here:
How to get first day of a given week number in Java
(8 answers)
Closed 6 years ago.
Is there any way using any library to do something like this.
DateTime getStartingDate(String year, int weekNo){
//should return the starting day of the given weekNo of the given year.
}
Ex: year = 2016 weekNo=1
DateTime returning = 3rd Jan in (Sun-Sat format)
= 4th Jan in (Mon-Sun format)
It seems that you want, as a starting point, the first full week that starts on a given day of week (Sunday or Monday in your example).
This could be achieved with something like this:
import static java.time.temporal.TemporalAdjusters.nextOrSame;
public static LocalDate getStartingDate(int year, int weekNo, DayOfWeek weekStart) {
//should check that arguments are valid etc.
return Year.of(year).atDay(1).with(nextOrSame(weekStart)).plusDays((weekNo - 1) * 7);
}
or as an alternative:
return Year.of(year).atDay(1).with(ALIGNED_WEEK_OF_YEAR, weekNo).with(nextOrSame(weekStart));
And you call it like this:
import static java.time.DayOfWeek.MONDAY;
import static java.time.DayOfWeek.SUNDAY;
System.out.println(getStartingDate(2016, 1, SUNDAY)); //2016-01-03
System.out.println(getStartingDate(2016, 1, MONDAY)); //2016-01-04

Gregorian Calendar month of year [duplicate]

This question already has answers here:
Why is January month 0 in Java Calendar?
(18 answers)
Closed 8 years ago.
All I must do for this code is display the current year, month and day of the year using the GregorianCalendar class. for some reason everything is right but the month. The program returns the month as being 11 instead of 12. Any suggestions?
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
GregorianCalendar Calendar = new GregorianCalendar();
int year = Calendar.get (GregorianCalendar.YEAR);
int month = Calendar.get (GregorianCalendar.MONTH);
int day = Calendar.get (GregorianCalendar.DAY_OF_MONTH);
System.out.println("the current year is " + year);
System.out.println("the current month is " + month);
System.out.println("the current day is " + day);
}
Java stores the month numbers as 0-based in Calendar. When you use MONTH, 11 does represent December, so this is correct. You must add 1 to this output to convert to what we're used to -- a range of 1-12.
The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0
just add +1, java is counting months starting from 0 i.e.
GregorianCalendar.JANUARY == 0
Calendar.MONTH is zero-based. Because of this it is 11.
From the API:
The first month of the year is JANUARY which is 0; the last depends on
the number of months in a year.

Categories

Resources