Reputation: 3565
I have a calendar object as below that represents 08 Aug 2014
.It is a Friday. So myCal.get(Calendar.DAY_OF_WEEK)
should be 6. But it gives 2. Why is that?
java.util.GregorianCalendar[time=1410177767000,areFieldsSet=true,lenient=true,zone=Asia/Calcutta,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=8,WEEK_OF_YEAR=37,WEEK_OF_MONTH=2,DAY_OF_MONTH=8,DAY_OF_YEAR=251,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=5,HOUR_OF_DAY=17,MINUTE=32,SECOND=47,MILLISECOND=0,ZONE_OFFSET=19800000,DST_OFFSET=0]
Upvotes: 9
Views: 8445
Reputation: 340118
Use java.time classes rather than terrible legacy date-time classes with their crazy month numbering.
LocalDate // Represent a date-only value, without time-of-day, without offset, without time zone.
.of( 2014 , 8 , 8 ) // Or use `Month.AUGUST`.
.getDayOfWeek() // Returns `DayOfWeek` enum object.
.equals( DayOfWeek.FRIDAY ) // Returns true/false.
true
You are using terrible app old date-time classes that were supplanted years ago by the java.time classes.
Represent a date-only value with LocalDate
. Note the sane numbering, unlike the legacy classes: 2014
means the year 2014, and months 1-12 mean January-December. So your problem of inadvertently using the wrong month is moot, and never would have occurred if you’d been using the modern and well-designed java.time classes.
LocalDate ld = LocalDate.of( 2014 , 8 , 8 ) ;
For more clarity, use the Month
enum. So month 8 is Month.AUGUST
.
LocalDate ld = LocalDate.of( 2014 , Month.AUGUST , 8 ) ;
Ask for the DayOfWeek
enum object representing the day-of-week on that date.
DayOfWeek dow = ld.getDayOfWeek() ;
If you have a GregorianCalendar
object in hand given by old code not yet updated to java.time, convert. Convert to a ZonedDateTime
. Then extract the DayOfWeek
.
ZonedDateTime zdt = myGregCal.toZonedDateTime() ;
DayOfWeek dow = zdt.getDayOfWeek() ;
Upvotes: 1
Reputation: 796
As our friends said, the count starts from 0. So, January is month 0.
If you came here probably you have the code already done. In order to avoid reviews in code you could do:
currentDateMonth = calendar.get(Calendar.MONTH);
currentDateMonth = currentDateMonth+1;
Upvotes: 0
Reputation: 533
The GregorianCalender takes month for august as '7' and not '8' since January is represented as '0'. Reference : Gregorian Calendar
So kindly check the following and it should work.
import java.util.*;
public class Test {
public static void main(String args[]) {
GregorianCalendar myCal = new GregorianCalendar(2014, 7, 8);
System.out.println(myCal.get(Calendar.DAY_OF_WEEK));
}
}
Upvotes: 4
Reputation: 500893
I have a calendar object as below that represents 08 Aug 2014.
It doesn't: MONTH=8
is September, not August (month numbering starts from zero).
You can verify yourself by noting DAY_OF_YEAR=251
in your output. The 251st day of a non-leap year is 8 September.
Another way to check the timestamp is by pasting 1410177767000
into http://www.epochconverter.com/
Upvotes: 16