Gregorian Calendar month of year [duplicate] - java

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.

Related

LocalDate wrong output with WeekFields [duplicate]

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.

4-4-5 Calendar approach based on Java 8 Code

For my Fiscal Calendar in Power BI I am currently trying to implement the 4-4-5 approach.
Our calendar works with 4-4-5 week quarters. Since this only has 364 days each year, there must be a 53 week year after a few years. As a result, December has 6 instead of 5 weeks.
Unfortunately, there is still no approach based on DAX.
In another post here, however, I found a JAVA code, which probably determines whether the year has 53 weeks or not:
calculate number of weeks in a given year
private static long getNumberOfWeeksInYear(LocalDate date) {
LocalDate middleOfYear = date.withDayOfMonth(1).withMonth(6);
return middleOfYear.range(WeekFields.ISO.weekOfWeekBasedYear()).getMaximum();
}
public static void main(String[] args) {
for (int year = 2000; year < 2400; year++) {
long numberOfWeeks = getNumberOfWeeksInYear(LocalDate.of(year, 1, 1));
if (numberOfWeeks != 52) {
System.out.println(year + " has " + numberOfWeeks + " weeks");
}
}
}
Do any of you know how to translate the code into Dax?
Our Fiscal Calendar starts not based on the gregorian calendar.
This year starts at 30.12.19 and ends 03.01.21. This year has 53 weeks.
I cannot help with PowerPivot and DAX. But I can tell you how to get those information usingExcel formulas.
Given the year in A2 you can calculate the Monday of the first ISO calendar week in that year using following formula:
=DATE($A2,1,1)-WEEKDAY(DATE($A2,1,1),3)+(ISOWEEKNUM(DATE($A2,1,1)-WEEKDAY(DATE($A2,1,1),3))<>1)*7
You can calculate the Sunday of the last ISO calendar week in that year using following formula:
=DATE($A2+1,1,1)-WEEKDAY(DATE($A2+1,1,1),3)+(ISOWEEKNUM(DATE($A2+1,1,1)-WEEKDAY(DATE($A2+1,1,1),3))<>1)*7-1
Given the Sunday of the last ISO calendar week placed in C2, following formula calculates the number of ISO weeks of that year:
=ISOWEEKNUM($C2)
Example:
As you see, the years are from A2 downwards. Formula to calculate the Monday of the first ISO calendar week is placed in B2 downwards. Formula to calculate the Sunday of the last ISO calendar week is in C2 downwards. And the formula to calculate the number of ISO weeks of that year is in D2 downwards.

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()));

Random date for year 2014 java [duplicate]

This question already has answers here:
Generate random date of birth
(15 answers)
Closed 8 years ago.
I want to generate a random date as string in format - yy-MM-dd for the given year.
assume if i pass the year it should give a random date of the year.
I went through Random() as well as nextInt() but not sure how to get this
could you please help me on how to achieve this?
Thanks.
You can use a Calendar to do that:
final Calendar cal = Calendar.getInstance();
final Random rand = new Random();
final SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd");
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.DAY_OF_YEAR, rand.nextInt(cal.getActualMaximum(Calendar.DAY_OF_YEAR)) + 1);
System.out.println(format.format(cal.getTime()));
cal.getActualMaximum(Calendar.DAY_OF_YEAR) will return the number of the last day of the year the Calendar is set to (2014 in this code).
rand.nextInt() will return a number between 0 (inclusive) and the number of the last day (exclusive). You have to add 1 because the field Calendar.DAY_OF_YEAR starts at 1.
cal.set() will set the given field of the Calendar to the value given as the second argument. It is used here to set the year to 2014, and the day of the year to the random value.
SimpleDateFormat is used to print the date in the required format.
You can do with JSR-310 (Built in Java 8, but available to older versions)
public static LocalDate randomDateIn(int year) {
Year y = Year.of(year);
return y.atDay(1+new Random().nextInt(y.length()));
}
System.out.println(randomDateIn(2014));
prints something like
2014-05-21
If you want to work with random, this is how it works:
Random r=new Random();
int day=r.nextInt(30)+1; // (think of something yourself for implementing months with different amount of days)
int month=r.nextInt(11)+1; // (+1 because you don't want the zero)
However i see another answer, which if it works will probably save you a lot of time on implementing the days each month has.(and the leap year)

Im trying to calculate the number off days between 2 date objects [duplicate]

This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 8 years ago.
public static int countWeeks() {
// setting dates
Calendar calStart = GregorianCalendar.getInstance();
calStart.set(2014, 8, 30);
Date dateStart = calStart.getTime();
Date dateEnd = new Date();
// count days and weeks
int diffInDays = Days.daysBetween(new DateTime(dateStart), new DateTime(dateEnd)).getDays(); // int weekNumber = (int) diffInDays / 7;
return weekNumber;
}
I'm trying to calculate the number of days and weeks between today and last week but I always get -3 as weekNumber. I have no idea what i'm doing wrong.
Thanks in advance.
First, I will assume that
int weekNumber = (int) diffInDays / 7;
is not commented since otherwise you would get a compilation error.
Now, as explained in my comment, by doing
calStart.set(2014, 8, 30);
You are setting the date at the end of setember, not of august. So, it is 3 weeks ahead of now, so you get a -3. Use the Calendar constants.
calStart.set(2014, Calendar.AUGUST, 30);
You set the startdate to Sep. 30th because te month is zero bases!
See the documentation from java.util.Calendar:
public final void set(int year,
int month,
int date) Sets the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH. Previous values of other calendar fields are
retained. If this is not desired, call clear() first. Parameters: year
- the value used to set the YEAR calendar field. month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0
for January. date - the value used to set the DAY_OF_MONTH calendar
field. See Also:
You are getting -3 as the weeknumber since you have commented that out so it showing some random value. Also note that 8 shows the September month not Aug since months are 0 based.
So if you are aiming at August month then you may try this:
calStart.set(2014, 7, 30);
^^-- This represents August month
If you are on Java 8 you can use the Java time API:
LocalDate start = LocalDate.of(2014, 8, 30);
LocalDate end = LocalDate.now();
long days = ChronoUnit.DAYS.between(start, end);
return (int) days / 7;

Categories

Resources