Hello i'm using a Calendar
in Java
What I want is to change my Calendar value, and have the following / previous week.
I tried
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, cal.DATE-7);
But it acts weird
Hello i'm using a Calendar
in Java
What I want is to change my Calendar value, and have the following / previous week.
I tried
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, cal.DATE-7);
But it acts weird
You should use something like the following instead:
c.add(Calendar.WEEK_OF_YEAR, -1);
Your code is completely wrong.
cal.DATE-7
does not mean "7 days before today". Calendar.DATE
is just a constant that specifies the field type for Calendar
.
Next week.
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.plusWeeks( 1L )
Last week.
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.minusWeeks( 1L )
The modern way is with the java.time classes that supplant the troublesome old legacy classes such as Calendar
& Date
.
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without 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(!).
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Adding or subtracting weeks with a LocalDate
is easy. Call the plusWeeks
or minusWeeks
methods.
LocalDate nextWeek = today.plusWeeks( 1L );
LocalDate lastWeek = today.minusWeeks( 1L );
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?
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.
You'll have to do something like this:
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
System.out.println(cal.getTime());
cal.set(Calendar.WEEK_OF_YEAR, cal.get(Calendar.WEEK_OF_YEAR)-1);
System.out.println(cal.getTime());
}
Hope this helped, have Fun!