Calendar allways returns the same date - android

I'm trying to get the current day of the week and week of the year like this:
Declaring my variable like this:
Calendar calWeek;
Calendar calDay;
Setting the values like this:
calWeek = Calendar.getInstance();
calWeek.setFirstDayOfWeek(Calendar.MONDAY);
calWeek.set(Calendar.WEEK_OF_YEAR, Calendar.MONDAY);
calDay = Calendar.getInstance();
calDay.setFirstDayOfWeek(Calendar.MONDAY);
calDay.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
int currentWeek = calWeek.get(Calendar.WEEK_OF_YEAR);
int dayInWeek = calDay.get(Calendar.DAY_OF_WEEK);
currentWeek returns 2 and dayInWeek returns 2. The current week is 1 and it's Wednesday. (3rd day of the week)
Even if i change the date on my device, the output is the same, currentWeek returns 2 and dayInWeek returns 2.
Why does it always return the same date?
Best regards,
Dridia

As mentioned in Mike M's comment: you set both values to Calendar.MONDAY which is equals to 2.
Calendar.getInstance() returns an instance with the current date but if you call calendarInstance.get(Calendar.WEEK_OF_YEAR) you still get 2 because according to the docs:
When setting or getting the WEEK_OF_MONTH or WEEK_OF_YEAR fields, Calendar must determine the first week of the month or year as a reference point. The first week of a month or year is defined as the earliest seven day period beginning on getFirstDayOfWeek() and containing at least getMinimalDaysInFirstWeek() days of that month or year....
I just tried it and getMinimalDaysInFirstWeek()returns 1 by default. So you should set this to 7 days. So the first Week will begin on Monday as you expect.
One instance of Calendar is sufficient and your code should look like this:
Calendar calendarInstance = Calendar.getInstance();
calendarInstance.setFirstDayOfWeek(Calendar.MONDAY);
calendarInstance.setMinimalDaysInFirstWeek(7);
int currentWeek = calendarInstance.get(Calendar.WEEK_OF_YEAR);
int dayInWeek = calendarInstance.get(Calendar.DAY_OF_WEEK);
System.out.println("week = " + currentWeek);
System.out.println("day of week = " + dayInWeek);
prints:
week = 1
day of week = 4
P.S. 4 means Wednesday

Related

Calendar display wrong starting day in android?

I have used below library for calendar but it display firstdayofweek is Monday i want to start day with sunday.
https://github.com/Applandeo/Material-Calendar-View
I have changed code accordingly but it still display date accordingly monday is firstday.
ArrayList<Date> days = new ArrayList<>();
// Get Calendar object instance
Calendar calendar = (Calendar) mCalendarProperties.getCurrentDate().clone();
// Add months to Calendar (a number of months depends on ViewPager position)
calendar.add(Calendar.MONTH, position);
// Set day of month as 1
calendar.set(Calendar.DAY_OF_MONTH, 1);
// Get a number of the first day of the week
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
// Count when month is beginning
int monthBeginningCell = dayOfWeek + (dayOfWeek == 1 ? 5 : -2);
// Subtract a number of beginning days, it will let to load a part of a previous month
calendar.add(Calendar.DAY_OF_MONTH, -monthBeginningCell);
/*
Get all days of one page (42 is a number of all possible cells in one page
(a part of previous month, current month and a part of next month))
*/
while (days.size() < 42) {
days.add(calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
mPageMonth = calendar.get(Calendar.MONTH) - 1;
CalendarDayAdapter calendarDayAdapter = new CalendarDayAdapter(this, mContext,
mCalendarProperties, days, mPageMonth);
mCalendarGridView.setAdapter(calendarDayAdapter);
Try this:
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);

get start and end date of the week

Actually i want to display a set of data with the start and end date of the week were that particular date falls on. In my emulator its working fine. Eg. If i give Apr 23 its giving me start date of the week as 22 Apr and end date as 28 Apr, but if i try to build the same code in my device its showing start date of the week as 27 Apr and end date as 28 Apr.
Piece of Code which i am using:
//to get first day of week
cal1.set(Calendar.DAY_OF_WEEK, 1);
int day1 = cal1.get(Calendar.DAY_OF_MONTH);
//to get last day of week
cal1.set(Calendar.DAY_OF_WEEK, 7);
int day7 = cal1.get(Calendar.DAY_OF_MONTH);
I don't know why you getting that data but this is how I get the first and last date, take look might help. (its written to give current week's first and last date, so might have to tweak it little bit.)
Calendar calendar = Calendar.getInstance();
Date date1 = calendar.getTime();
//current date to check that our week lies in same month or not
SimpleDateFormat checkformate = new SimpleDateFormat("MM/yyyy");
String currentCheckdate= checkformate.format(date1);
int weekn = calendar.get(Calendar.WEEK_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
//resat calender without date
calendar.clear();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.WEEK_OF_MONTH,weekn);
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.YEAR,year);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date datef = calendar.getTime();
//move date to 6 days + to get last date of week
Long timeSixDayPlus = calendar.getTimeInMillis()+518400000L;
Date dateL = new Date(timeSixDayPlus);
String firtdate = simpleDateFormat.format(datef);
String lastdate = simpleDateFormat.format(dateL);
String firtdateCheck = checkformate.format(datef);
String lastdateCheck = checkformate.format(dateL);
//if our week lies in two different months then we show only current month week part only
if (!firtdateCheck.toString().equalsIgnoreCase(currentCheckdate)) {
firtdate = "1" + "/" + calendar.get(Calendar.MONTH) + "/" + calendar.get(Calendar.YEAR);
}
if (!lastdateCheck.toString().equalsIgnoreCase(currentCheckdate)) {
int ma = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
lastdate = String.valueOf(ma) + "/" + calendar.get(Calendar.MONTH) + "/" + calendar.get(Calendar.YEAR);
}
Log.e("current","=>>"+firtdate+" to "+lastdate);
To get the first day of the week -
initialize the Calendar as per your need. in this case, I am getting the current date calendar.
set the current day of the week to the first day of the week.
get the corresponding date.
Calendar calendar = Calendar.getInstance();
//optional step
calendar.setFirstDayOfWeek(Calendar.SUNDAY);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
int firstDateOfWeek = calendar.get(Calendar.DATE);
To get the last date of the week -
follow the step as above to initialize.
set the day of the week as Saturday.
get the corresponding date.
Calendar calendar = Calendar.getInstance();
//optional step
calendar.setFirstDayOfWeek(Calendar.SUNDAY);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
int lastDateOfWeek = calendar.get(Calendar.DATE);
In this way, you can get eh first and the last date for the week. one thing to keep in mind that I have set the first day of the week as SUNDAY. set as per your need. although it is purely optional to set the first day of the week. this gives you a more transparency in code.

Android CalendarView: cannot set min date and selected date

I know the Android CalendarView is among the buggiest piece of software in human history, but I must use it so came here asking.
I need to open a CalendarView with:
minimum date set to today;
selected date set to today.
This is how I do it:
int day = 8;
int month = 2;
int year = 2015;
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
CalendarView calendarView = (CalendarView) findViewById(R.id.calendarView);
calendarView.setMinDate(calendar.getTimeInMillis()-2000);
calendarView.setDate(calendar.getTimeInMillis(), true, false);
fixIncredibleBugOfCalendarView(calendarView, calendar);
calendarView.setOnDateChangeListener(this);
When I run the previous code, the CalendarView:
shows the 9th of March as the first selectable day, instead of the 8th (DAY_OF_MONTH starts from 1);
shows the 15th of March as the selected date;
So I have geniously decided to include the two lines marked with *:
int day = 8;
int month = 2;
int year = 2015;
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
CalendarView calendarView = (CalendarView) findViewById(R.id.calendarView);
calendar.add(Calendar.DAY_OF_MONTH, -1); // * - subtract one day, i.e. March 7
calendarView.setMinDate(calendar.getTimeInMillis());
calendar.add(Calendar.DAY_OF_MONTH, 1); // * add one day, back to 8
calendarView.setDate(calendar.getTimeInMillis(), true, false);
fixIncredibleBugOfCalendarView(calendarView, calendar);
calendarView.setOnDateChangeListener(this);
In the first line I remove one day, in the second I add one.
With these two more lines, my CalendarView shows:
the 7th of March, as the first selectable date;
the 15th of March, as the selected date.
The method fixIncredibleBugOfCalendarView(...) should fix something (I found it on SO):
private void fixIncredibleBugOfCalendarView(CalendarView cal, Calendar date) {
// Workaround for CalendarView bug relating to setMinDate():
// https://code.google.com/p/android/issues/detail?id=42750
// Set then reset the date on the calendar so that it properly
// shows today's date. The choice of 24 months is arbitrary.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
date.add(Calendar.MONTH, 24);
cal.setDate(date.getTimeInMillis(), false, true);
date.add(Calendar.MONTH, -24);
cal.setDate(date.getTimeInMillis(), false, true);
}
}
This should not be so hard and I do not think it's a bug: it is more likely that it's my fault. Two questions: Could you please be so kind to tell me how to:
tell CalendarView the minimum date it should display?
have CalendarView showing as selected what I decide is the selected date?
Cheers
This is late, probably you have already solved the thing . But Here is my code to solve it
android.icu.util.Calendar c = android.icu.util.Calendar.getInstance();
Long min = c.getTime().getTime();
Long max = 2629746000L + c.getTime().getTime();
CalendarView cv = (CalendarView) findViewById(R.id.date_picker);
cv.setMinDate(min);
cv.setMaxDate(max);
You can also CalenderView just needs to have mindate in long format. You can also go for java
Data d = new Date();
d.getTime();
But Somehow it doesnt work because of current TimeZone.
Instead Calender returns a dateObject with respect to Current TimeZone set.

Android converting calendar in one TimeZone to local TimeZone

I am using following code to convert timezone (GMT-3) to device local timezone.
int hour=17,minute=0,day=12,month=6,year=2014;
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-3"));
cal.set(year, (month-1), day,hour,minute);
cal.setTimeZone(TimeZone.getDefault());
Log.d("Time", cal.get(Calendar.DATE)+"/"+cal.get(Calendar.MONTH)+"/"+cal.get(Calendar.YEAR)+" , "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+" "+cal.get(Calendar.AM_PM));
My local timezone is GMT+5:30
Expected result is
Time 13/5/2014, 1:30 0
But I am getting the result
12/5/2014 , 13:30 1
Sorry for you, GregorianCalendar is sometimes the hell. Your problem is following:
If you immediately set the timezone after having set the fields for year, month etc. then this mutable calendar class will only shift the timezone retaining the already set fields containing the local time. Those fields for year, month etc. will NOT be recalculated. This behaviour causes a shift on the global timeline represented by cal.getTime(), too.
In order to force the calendar object to recalculate the fields you need to call a getter. Watch out for following code and especially remove the comment marks to see the effect.
int hour = 17, minute = 0, day = 12, month = 6, year = 2014;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
TimeZone tz1 = TimeZone.getTimeZone("GMT-3");
sdf.setTimeZone(tz1);
Calendar cal = new GregorianCalendar(tz1);
cal.set(year, (month - 1), day, hour, minute);
// System.out.println(sdf.format(cal.getTime()));
// System.out.println("Hour=" + cal.get(Calendar.HOUR_OF_DAY));
TimeZone tz2 = TimeZone.getTimeZone("GMT+0530");
sdf.setTimeZone(tz2);
cal.setTimeZone(tz2);
System.out.println(sdf.format(cal.getTime()));
System.out.println("Hour=" + cal.get(Calendar.HOUR_OF_DAY));
Output with comment-disabled lines:
2014-06-12T17:00+0530
Hour=17
Output with enabled lines after having removed the comment marks:
2014-06-12T17:00-0300
Hour=17
2014-06-13T01:30+0530
Hour=1

Trouble getting Calendar.WEEK_OF_YEAR

I've been trying to get this to work for days and I'm tearing my hair out. I think I just need another pair of eyes to help me out.
I have "Entries" stored in a database, each with a Unix timestamp on the second they were entered. I have a system where the user can select any date and view the entries stored on the same week. The problem arises when I let the user set a custom first day of the week with Calendar.setFirstDayOfWeek(). I can never get a correct return value from the database with the first day of the week set to something other than Sunday (for this example, I'm using Tuesday).
public void getEntries() {
/* Make sure temp Calendar has same first day */
temp = Calendar.getInstance();
temp.setFirstDayOfWeek(date.getFirstDayOfWeek());
/* Common date ranges in unix time */
long oneday = 86400000L;
long oneweek = 604800000L;
long onemonth = 2628000000L;
long oneyear = 31536000000L;
/* The custom date in unix time. For example, the user may have selected Dec. 1, 2012 */
long set_time = date.getTimeInMillis();
entries.clear();
dba.open();
/* This query gets entries within 1 week and 1 day of the user-set date just to be safe */
Cursor cc = dba.query("Date < " +(set_time+oneweek+oneday)+ " AND Date > " +(set_time-oneday-oneweek));
if(cc.moveToFirst()) do {
/* Set temp calendar to the timestamp of the entry in database */
long unix = cc.getLong(1);
temp.setTimeInMillis(unix);
System.out.println("Temp calendar set to "+temp.getTime().toGMTString()+ " fdow("+temp.getFirstDayOfWeek()+") week("+temp.get(Calendar.WEEK_OF_YEAR)+"), user calendar set to "+date.getTime().toGMTString()+" fdow("+date.getFirstDayOfWeek()+") week("+date.get(Calendar.WEEK_OF_YEAR)+")");
if(temp.get(Calendar.WEEK_OF_YEAR) == date.get(Calendar.WEEK_OF_YEAR)
&& temp.get(Calendar.YEAR) == date.get(Calendar.YEAR) )
/* Entry object is instantiated and added to ArrayList if WEEK_OF_YEAR in temp calendar matches WEEK_OF_YEAR in global calendar */
entries.add(createEntryFromCursor(cc));
} while(cc.moveToNext());
}
In my tests, I know for a fact there is an entry at Nov. 30, 2012. With a first day of week set to Tuesday (and the entry was on Friday), this should return 1 result if the user sets the date as 1 Dec, and no result if the user sets 26 Nov. (a Monday). However, I get 1 result for both. What's wrong?!
Edit
I still really need help! I've updated the above with my current code. I'm still getting odd results. For example, with a first day of week as Monday, I'm getting this from System.out:
12-09 11:46:38.465: I/System.out(15130): Temp calendar set to 9 Dec 2012 19:29:59 GMT fdow(2) week(49), user calendar set to 9 Dec 2012 14:51:59 GMT fdow(2) week(50)
This is saying that 9 Dec, 2012 occurs in 2 different WEEK_OF_YEARs (49/50) even though both calendars have the first day of week equal to 2. Umm.. what??
Solution
I ditched getting the WEEK_OF_YEAR and followed the suggestion to get the start and end Dates for the week.
// get rollback amt
temp.setTimeInMillis(set_time);
int rollback = 0;
int dayofweek = date.get(Calendar.DAY_OF_WEEK);
while(dayofweek != temp.getFirstDayOfWeek()) {
dayofweek--;
if(dayofweek == 0) dayofweek = 7;
rollback--;
}
int rollfwd = rollback + 6;
// get start bound
temp.setTimeInMillis(set_time);
temp.roll(Calendar.DAY_OF_YEAR, rollback);
temp.set(Calendar.HOUR_OF_DAY, 0);
temp.set(Calendar.MINUTE, 1);
Date start = temp.getTime();
// get end bound
temp.setTimeInMillis(set_time);
temp.roll(Calendar.DAY_OF_YEAR, rollfwd);
temp.set(Calendar.HOUR_OF_DAY, 23);
temp.set(Calendar.MINUTE, 59);
Date end = temp.getTime();
Then I can check if the Date of the Entry is between those:
if(entrydate.after(start) && entrydate.before(end))
Can you use SimpleDateFormat in android to get week_of_year and validate the conditions for querying the user selected date.
Step 1: Get user choice for selecting the week.
eg:27
Step 2: get start of the week and ending of the week.
start of 27th week to end of 27th week.
Step 3: Use this two boundary conditions to filter your result set.
Hope this will help you to resolve your issue.
12-09 11:46:38.465: I/System.out(15130): Temp calendar set to 9 Dec
2012 19:29:59 GMT fdow(2) week(49), user calendar set to 9 Dec 2012
14:51:59 GMT fdow(2) week(50)
There is nearly a 5 hour difference between your Temp calendar value and your user calendar value.
You are outputting the date string using GMT:
temp.getTime().toGMTString()
while your Calendar objects will use the local timezone.
temp.get(Calendar.WEEK_OF_YEAR)+")
It is possible that these times are on the same day/week in GMT but not in your local timezone.
This will give you the days since monday of tha tweek
int daysSinceMonday = (7 + calendar.get(Calendar.DAY_OF_WEEK) - Calendar.MONDAY) % 7;
Use this to re-calculate the begining of your week.

Categories

Resources