I have been looking and searching a lot for this question. I'm really stupid when it comes to using the JAVA Calendar class.
Could anybody please help me to show a simple way of how to get the current time (on the android phone) and check whether is the first Sunday of the month or not.
// Comments in the code examples are very welcome :-)
Calendar cal = Calendar.getInstance();
if (Calendar.SUNDAY == cal.get(Calendar.DAY_OF_WEEK) && cal.get(Calendar.DAY_OF_MONTH) <= 7)
I thought about adding some explanation but this code is pretty self explanatory...
Calendar rightNow = Calendar.getInstance();
int weekDay = rightNow.get(Calendar.DAY_OF_WEEK);
int monthDay = rightNow.get(Calendar.DAY_OF_MONTH);
if ( (weekDay == Calendar.SUNDAY) && (monthDay <8)) {
// first sunday of this month
}
Simply check if the date is a Sunday and if the date is less than 8...
I'm sure there are better ways, but this would be the simplest.
Calendar cal = Calendar.getInstance();
cal.setDate(myDate);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
if(dayOfWeek == Calendar.SUNDAY && dayOfMonth < 8){
}
Also there is a cal.get(Calendar.WEEK_OF_MONTH)
which you could use for comparison instead of of checking if dayOfMonth < 8
just do weekOfMonth == 0
could be 1 instead of 0.
To get the current time use this:
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minutes = now.get(Calendar.MINUTE));
To see if today is the first Sunday in a Month use
Calendar now = Calendar.getInstance();
int day = now.get(Calendar.DAY_OF_WEEK);
if (day == Calendary.Sunday) // today is a Sunday
{
int day_num = now.get(Calendar.DAY_OF_MONTH);
if (day_num <= 7) // the day number is within the 1st 7 days of the month
{
// this is the 1st sunday in the month
}
}