Calendar get year returns wrong result - java

I want to create a calendar object and set it to a certain year and a week in that year.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR, weekOfYear); // 1
calendar.set(Calendar.YEAR, year); // 2016
setWeekChecked(calendar);
This is the toString of the calendar object as I pass it to the setWeekChecked method:
java.util.GregorianCalendar[time=?,areFieldsSet=false,lenient=true,zone=America/New_York,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2016,MONTH=0,WEEK_OF_YEAR=1,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=7,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=5,HOUR_OF_DAY=5,MINUTE=25,SECOND=43,MILLISECOND=219,ZONE_OFFSET=-18000000,DST_OFFSET=0]
In the setWeekChecked method:
public void setWeekChecked(final Calendar cal) {
final int targetWeek = cal.get(Calendar.WEEK_OF_YEAR); // Returns 1
final int targetYear = cal.get(Calendar.YEAR); // Returns 2015??
}
This is the toString of the calendar object now:
java.util.GregorianCalendar[time=1451557543219,areFieldsSet=true,lenient=true,zone=America/New_York,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2015,MONTH=11,WEEK_OF_YEAR=1,WEEK_OF_MONTH=5,DAY_OF_MONTH=31,DAY_OF_YEAR=365,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=5,AM_PM=0,HOUR=5,HOUR_OF_DAY=5,MINUTE=25,SECOND=43,MILLISECOND=219,ZONE_OFFSET=-18000000,DST_OFFSET=0]
What am I doing wrong?

I suspect that the calendar is trying to use the current day-of-week (it's Thursday today) in the first week of 2016.
Now, looking at your calendar settings, you've got firstDayOfWeek=1 (so weeks run Sunday to Saturday) and minimalDaysInFirstWeek=1 (so the first week of the year is the one that includes January 1st).
That means that the first week of 2016 in your calendar ran from Decemember 27th 2015 to January 2nd 2016. Therefore Thursday in the first week was December 31st - which is exactly what the calendar you've shown us says.
Fundamentally, calendar arithmetic with "week of year" is tricky because:
There are lots of different culture-specific ways of looking at them
Typically requirements don't specify which of those you're actually interested in
I'd strongly recommend using Joda Time if at all possible to make your date/time-handling code clearer to start with, but you'll still need to work out exactly what you mean by "set it to a certain year and a week in that year". Note that Joda Time separates the concepts of "week-year" (used with week-of-week-year and day-of-week) from "year" (used with month and day-of-month) which helps greatly. You need to be aware that for a given date, the week-year and year may be different.

tl;dr
LocalDate.of( 2016 , Month.JULY , 1 )
.with( IsoFields.WEEK_OF_WEEK_BASED_YEAR , 1 )
Details
The Answer by Jon Skeet is correct. Update: We have a better way.
The java.time classes built into Java 8 and later supplant the troublesome old legacy date-time classes bundled with the earliest versions of Java. And java.time officially supplants Joda-Time, as that project is now in maintenance mode.
As Skeet points out, there are different ways to define week-of-year.
The java.time classes provide support for the standard ISO 8601 definition of week-of-year. This definition is that week number 1 is the first week with a Thursday, and that week starts on a Monday. So the beginning of the week may include one or more days of the previous year, and the last week may include one or more days from the following year. The year always has either 52 or 53 weeks.
See my Answer to a similar Question for more details.
The LocalDate class represents a date-only value without time-of-day and without time zone.
Get a date near the middle of the desired year. That desired year is a week-based year rather than a calendar year, so must avoid the very beginning or ending of the calendar year. In your case, you wanted week-based year of 2016.
LocalDate ld = LocalDate.of( 2016 , Month.JULY , 1 ) ;
Next we adjust that date into the desired week by using IsoFields.WEEK_OF_WEEK_BASED_YEAR.
LocalDate dayIn2016W01 = ld.with( IsoFields.WEEK_OF_WEEK_BASED_YEAR , 1 ) ;
If you want the first day of that week, use another TemporalAdjuster from the TemporalAdjusters class.
LocalDate firstDayOf2016W01 = dayIn2016W01.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) );
Tip: When Android becomes more capable, use the YearWeek class from the ThreeTen-Extra project.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

Related

Java current date minus 3 months and start from month begining [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I need to get statistics for a quarter.
Example: today is February 10th 2018, I need to retrieve data from December 2017, from 1st to 31st, then from January 2018, from 1st to 30th and from February 1st to current date.
How can I achieve this using Java Date?
tl;dr
YearMonth.now().minusMonths( 1 ).atEndOfMonth() // or .atDay( 1 )
Details
Get today’s date.
ZoneId z = ZoneId.of( “Africa/Tunis” ) ;
LocalDate today = LocalDate.now( z ) ;
Get the year-month of that date.
YearMonth ymCurrent = YearMonth.from( today ) ;
Add the ThreeTen-Extra library to your project to access the LocalDateRange class. This class represents as one object a pair of LocalDate objects, start date and stop date, for a date range from one date to the other date.
LocalDateRange rangeCurrent = LocalDateRange.ofClosed( ymCurrent.atDay( 1 ) , today ) ;
Move to previous month.
YearMonth ymPrevious = ymCurrent.minusMonths( 1 ) ;
LocalDateRange rangePrevious = LocalDateRange.ofClosed( ymPrevious.atDay( 1 ) , ymPrevious.atEndOfMonth() ) ;
Subtract yet another time for your third month.
Tip: Consider using the Half-Open approach to defining a span of time, where the beginning is inclusive while the ending is exclusive. So a month starts with the first day of the month and runs up to, but does not include, the first day of the following month.
For another valid approach using java.time classes, see the Answer by diston.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Try something like this:
// Get current date
Calendar start;
start = Calendar.getInstance();
// Go to beginning of month
start.set(Calendar.DAY_OF_MONTH, 1);
start.set(Calendar.HOUR_OF_DAY, 0);
start.set(Calendar.MINUTE, 0);
start.set(Calendar.SECOND, 0);
start.set(Calendar.MILLISECOND, 0);
// Go 2 months back
my_date.add(Calendar.MONTH, -2);
// Get end of same month
Calendar end;
end = start.clone();
end.add(Calendar.MONTH, 1);
end.add(Calendar.DAY_OF_MONTH, -1);
Then, do something similar for the other months
You can use Java 8's java.time classes (or threeten backport for Java <= 7).
If you'll work only with day/month/year and don't care about hours and timezones, the best class to use is LocalDate. To create a specific date is easy:
// February 10th 2018
LocalDate current = LocalDate.of(2018, 2, 10);
Or you can call LocalDate.now() to get the current date.
Then, to get to December 1st 2017, you must subtract 2 months (2 months before February is December) and set the day to 1:
// start is December 1st 2017
LocalDate start = current
// 2 months ago = December
.minusMonths(2)
// change day of month to 1st
.withDayOfMonth(1);
Then you can loop from December 1st to February 10th:
LocalDate date = start;
while (date.isBefore(current)) {
// do whatever you need with the date
// go to the next day
date = date.plusDays(1);
}
Note that plusDays returns a new object, so I must assign it to the same variable, otherwise it won't be changed.
I also used isBefore, which doesn't include the current date in the loop - it'll stop at February 9th. If you want to include February 10th, change the condition to if (! date.isAfter(current))

AlarmManger doesn't work [duplicate]

This question already has answers here:
Why is January month 0 in Java Calendar?
(18 answers)
Closed 2 years ago.
Calendar rightNow = Calendar.getInstance();
String month = String.valueOf(rightNow.get(Calendar.MONTH));
After the execution of the above snippet, month gets a value of 10 instead of 11. How come?
Months are indexed from 0 not 1 so 10 is November and 11 will be December.
They start from 0 - check the docs
As is clear by the many answers: the month starts with 0.
Here's a tip: you should be using SimpleDateFormat to get the String-representation of the month:
Calendar rightNow = Calendar.getInstance();
java.text.SimpleDateFormat df1 = new java.text.SimpleDateFormat("MM");
java.text.SimpleDateFormat df2 = new java.text.SimpleDateFormat("MMM");
java.text.SimpleDateFormat df3 = new java.text.SimpleDateFormat("MMMM");
System.out.println(df1.format(rightNow.getTime()));
System.out.println(df2.format(rightNow.getTime()));
System.out.println(df3.format(rightNow.getTime()));
Output:
11
Nov
November
Note: the output may vary, it is Locale-specific.
As several people have pointed out, months returned by the Calendar and Date classes in Java are indexed from 0 instead of 1. So 0 is January, and the current month, November, is 10.
You might wonder why this is the case. The origins lie with the POSIX standard functions ctime, gmtime and localtime, which accept or return a time_t structure with the following fields (from man 3 ctime):
int tm_mday; /* day of month (1 - 31) */
int tm_mon; /* month of year (0 - 11) */
int tm_year; /* year - 1900 */
This API was copied pretty much exactly into the Java Date class in Java 1.0, and from there mostly intact into the Calendar class in Java 1.1. Sun fixed the most glaring problem when they introduced Calendar – the fact that the year 2001 in the Gregorian calendar was represented by the value 101 in their Date class. But I'm not sure why they didn't change the day and month values to at least both be consistent in their indexing, either from zero or one. This inconsistency and related confusion still exists in Java (and C) to this day.
Months start from zero, like indexes for lists.
Therefore Jan = 0, Feb = 1, etc.
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.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html
tl;dr
LocalDate.now() // Returns a date-only `LocalDate` object for the current month of the JVM’s current default time zone.
.getMonthValue() // Returns 1-12 for January-December.
Details
Other answers are correct but outdated.
The troublesome old date-time classes had many poor design choices and flaws. One was the zero-based counting of month numbers 0-11 rather than the obvious 1-12.
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
Now in maintenance mode, the Joda-Time project also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.
Months 1-12
In java.time the month number is indeed the expected 1-12 for January-December.
The LocalDate class represents a date-only value without time-of-day and without time zone.
Time zone
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
int month = today.getMonthValue(); // Returns 1-12 as values.
If you want a date-time for a time zone, use ZonedDateTime object in the same way.
ZonedDateTime now = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) );
int month = now.getMonthValue(); // Returns 1-12 as values.
Convert legacy classes
If you have a GregorianCalendar object in hand, convert to ZonedDateTime using new toZonedDateTime method added to the old class. For more conversion info, see Convert java.util.Date to what “java.time” type?
ZonedDateTime zdt = myGregorianCalendar.toZonedDateTime();
int month = zdt.getMonthValue(); // Returns 1-12 as values.
Month enum
The java.time classes include the handy Month enum, by the way. Use instances of this class in your code rather than mere integers to make your code more self-documenting, provide type-safety, and ensure valid values.
Month month = today.getMonth(); // Returns an instant of `Month` rather than integer.
The Month enum offers useful methods such as generating a String with the localized name of the month.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
cal.get(Calendar.MONTH) + 1;
The above statement gives the exact number of the month. As get(Calendar.Month) returns month starting from 0, adding 1 to the result would give the correct output. And keep in mind to subtract 1 when setting the month.
cal.set(Calendar.MONTH, (8 - 1));
Or use the constant variables provided.
cal.set(Calendar.MONTH, Calendar.AUGUST);
It would be better to use
Calendar.JANUARY
which is zero ...

java Calendar setFirstDayOfWeek not working

Here is the real calendar now:
March 2015
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
And I get DAY_OF_WEEK of 2015/3/24 like this:
public class TestCalendar {
public static void main(String[] argvs){
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(2015,Calendar.MARCH,24);
System.out.println(cal.get(Calendar.DAY_OF_WEEK));
}
}
Since I have cal.setFirstDayOfWeek to MONDAY the result I expecting is 2, but Whatever day I set to the first day of week(have tried SUNDAY and others) .It kept show me the same result which is 3. So It seemed that firstDayOfWeek won't affect the result.
Have I do something wrong?
EDIT
I just figured and thanks to answers below, that this setFirstDayOfWeek will not affect the result of get(Calendar.DAY_OF_WEEK) nor get(Calendar.WEEK_OF_YEAR)
Then what is this method setFirstDayOfWeek() designed for?
I mean How can I told the program that I want 2015/3/29 be the last day of the 12th week instead of treating it as the first day of the 13th week?
tl;dr
LocalDate.of( 2015 , Month.MARCH , 24 ) // `LocalDate` object for 2015-03-24.
.getDayOfWeek() // DayOfWeek.TUESDAY constant object
.getValue() // 2
Avoid legacy date-time classes
Calendar is a ugly mess, as are its sibling classes. Fortunately these old date-time classes are now legacy, supplanted by the java.time classes.
ISO 8601
If you want Monday as the first day of the week, Sunday the last, numbered 1-7, then use the ISO 8601 calendar used by default in the java.time classes.
DayOfWeek
The DayOfWeek enum hold predefined objects for each of those ISO days of the week. You can interrogate for its number if need be, though generally better to pass around objects of this enum rather than mere integers.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.of( 2015 , Month.MARCH , 24 );
DayOfWeek dow = ld.getDayOfWeek();
int value = dow.getValue(); // 1-7 for Monday-Sunday. But often better to use the `DayOfWeek` object rather than a mere integer number.
For working with other definitions of a week where Monday is not day number one, see the WeekFields class.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
cal.get(Calendar.DAY_OF_WEEK) will return you which day it is (SUNDAY, MONDAY, etc...) for the given date. So it will return you TUESDAY and then 3, whatever the first day of week is. This has nothing to do with the setFirstDayOfWeek method.
If you want to compute the number of day since the beginning of the week, you just have to get the first day of the week using getFirstDayOfWeek and do some simple math.
setFirstDayOfWeek just tells the Calendar which day is to be considered the first day,i.e., Sunday or Monday or any other day. It will not change the dayOfWeek for any arbitrary date. The javadoc for this method states the following:
public void setFirstDayOfWeek(int value)
Sets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France.
Parameters:
value - the given first day of the week.

Fetch the Month from yyy-MM-dd String [duplicate]

This question already has answers here:
Java SimpleDateFormat always returning January for Month
(4 answers)
Why is January month 0 in Java Calendar?
(18 answers)
Closed 1 year ago.
I have a date string "2012-01-26" which I get from JSON.
I have to now check if the month and year is as current year than display data it in ListView.
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-DD");
try {
Calendar c = Calendar.getInstance();
c.setTime(dateFormat.parse(event_start_date));
int month = c.get(Calendar.MONTH);
System.out.println(c.get(Calendar.YEAR));
System.out.println("month is"+month);
}
Year value is always correct, but the Month is always zero.What am I missing guys?
You are fetching month using Calendar's instance.
int month = c.get(Calendar.MONTH);
So you will get current month (i.e. January)
And it means 0. So the result is correct.
Check this.
month - The month that was set (0-11) for compatibility with Calendar.
If you want the month of event_start_date, then you won't have to use calendar's instance at all.
You can fetch it using
int month = event_start_date.getMonth();
java.time.YearMonth
The modern solution uses java.time classes defined in JSR 310.
If you are focused on the year and month without the day, use YearMonth class.
LocalDate ld = LocalDate.parse( "2012-01-26" ) ;
YearMonth ym = YearMonth.from( ld ) ;
int y = ym.getYear() ;
Month m = ym.getMonth() ;
String monthName = m.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
monthes start from 0 - which means youre getting JANUARY.
from Calendar.java:
public final static int JANUARY = 0;
The month is zero based (January = 0) so you have to add one.
read the java doc ;)
for MONTH it says:
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year is JANUARY which is 0; the last depends on the number of months in a year.
That's because month in Calendar start from 0 (for January) and go on till 11 (for December)

java get week of year for given a date

how can I get a week of the year given a date?
I tried the following code:
Calendar sDateCalendar = new GregorianCalendar();
sDateCalendar.set(Integer.parseInt(sDateYearAAAA), Integer.parseInt(sDateMonthMM)-1, Integer.parseInt(sDateDayDD));
System.out.format("sDateCalendar %tc\n", sDateCalendar);
iStartWeek = sDateCalendar.getWeekYear();
System.out.println("iStartWeek "+iStartWeek+ " "+sDateCalendar.WEEK_OF_YEAR);
and i obtain:
sDateCalendar lun apr 23 11:58:39 CEST 2012
iStartWeek 2012 3
while the correct week of year is 17. Can someone help me ?
tl;dr
For a year-week defined by the ISO 8601 standard as starting on a Monday and first week contains the first Thursday of the calendar year, use the YearWeek class from the ThreeTen-Extra library that adds functionality to the java.time classes built into Java.
org.threeten.extra.YearWeek
.from(
LocalDate.of( 2012 , Month.APRIL , 23 )
)
.toString()
2012-W17
Definition of a Week
You need to define week-of-year.
One common definition is that week # 1 has January 1.
Some mean week # 1 is the first week of the year holding the first day of the week (such as Sunday in the United States).
The standard ISO 8601 meaning is that week # 1 holds the first Thursday, and the week always begins with a Monday. A year can have 52 or 53 weeks. The first/last week can be have a week-based year different than the calendar year.
Beware that the old java.util.Calendar class has a definition of week that varies by Locale.
For many reasons, you should avoid the old java.util.Date/.Calendar classes. Instead use the new java.time framework.
java.time
Java 8 and later comes with the java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. See Tutorial.
Here is some example code to getting the ISO 8601 standard week.
Getting a date, and therefore a week, depends on the time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now( zoneId );
The IsoFields class defines a week-based year. We can ask for the:
Week-of-year number (WEEK_OF_WEEK_BASED_YEAR)
Year number of the week-based year (WEEK_BASED_YEAR).
First we get the current date-time.
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now ( zoneId );
Interrogate that date-time object, asking about the standard week-based year.
int week = now.get ( IsoFields.WEEK_OF_WEEK_BASED_YEAR );
int weekYear = now.get ( IsoFields.WEEK_BASED_YEAR );
Dump to console.
System.out.println ( "now: " + now + " is week: " + week + " of weekYear: " + weekYear );
now: 2016-01-17T20:55:27.263-05:00[America/Montreal] is week: 2 of weekYear: 2016
For more info, see this similar Question: How to calculate Date from ISO8601 week number in Java
WeekFields
In java.time you can also call upon the WeekFields class, such as WeekFields.ISO.weekBasedYear(). Should have the same effect as IsoFields in later versions of Java 8 or later (some bugs were fixed in earlier versions of Java 8).
YearWeek
For standard ISO 8601 weeks, consider adding the ThreeTen-Extra library to your project to use the YearWeek class.
YearWeek yw = YearWeek.of( 2012 , 17 ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
elegant way (no need for java.util.Calendar):
new SimpleDateFormat("w").format(new java.util.Date())
You are using sDateCalendar.WEEK_OF_YEAR, which is the static integer WEEK_OF_YEAR, see the source of the java.util.Calendar class:
public final static int WEEK_OF_YEAR = 3;
To get the week number, you should be using:
sDateCalendar.get(Calendar.WEEK_OF_YEAR);
Calendar calendar = Calendar.getInstance(Locale.WHATEVER);
calendar.set(year, month, day);
calendar.get(Calendar.WEEK_OF_YEAR);
Be careful with month in Calendar, as it starts with 0, or better use Calendar.WHATEVER_MONTH

Categories