get previous four weeks - android

My week start from Friday and end from Thursday, and i get a list of weeks of current month weeks.
In my Code every thing working fine but get current month four weeks but i want previous four weeks not next weeks of current week.
public void getWeeksOfMonth( int year) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
Calendar cal = Calendar.getInstance();
int currentmonth = cal.get(Calendar.MONTH);
int val = 0;
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, currentmonth);
cal.set(DAY_OF_MONTH, 1);
int ndays = cal.getActualMaximum(DAY_OF_MONTH);
System.out.println(ndays + "<<<ff");
while (cal.get(DAY_OF_WEEK) != FRIDAY) {
cal.add(DAY_OF_MONTH, 1);
ndays--;
}
int remainingDays = ndays % 7;
if (remainingDays == 0)
ndays += 7;
else
ndays = ndays + 7 - remainingDays;
int inc = 1;
for (int i = 1; i <= ndays; i++) {
String day = sdf.format(cal.getTime());
System.out.println(day + "<<<");
Log.e("quest", day + "<<<");
inc++;
if (val == 0) {
firstweek = day.substring(0, 6);
// weeklist.add(firstweek);
val = 1;
}
if (i % 7 == 0) {
String s = day.substring(0, 6);
weeklist.add(firstweek + " to " + s);
val = 0;
Log.e("weekdayss", "=======week days===========" + weeklist);
inc = 0;
}
if (inc >= 1 && i == ndays) {
for (int ii = inc; ii <= 6; ii++) {
String dayi = sdf.format(cal.getTime());
System.out.println(dayi + "<<<");
Log.e("quest1", dayi + "<<<");
inc++;
}
}
cal.add(Calendar.DATE, 1);
}
if (weeklist.size() == 5) {
weeklist.remove(4);
}
if (weeklist.size() == 6) {
weeklist.remove(5);
weeklist.remove(4);
}
}
Problem
Want to get previous four weeks, not current Month four weeks
OUTPUT
[
02-Mar to 08-Mar
09-Mar to 15-Mar
16-Mar to 22-Mar
23-Mar to 29-Mar
]

A good alternative is to use the threeten backport - in Android here's how to configure it. Or, if you're using API level >= 26, just use the java.time classes.
This API makes things much easier. You can use the WeekFields class to define your week (starting on Friday):
// week starts on Friday
WeekFields wf = WeekFields.of(DayOfWeek.FRIDAY, 1);
The first parameter (DayOfWeek.FRIDAY) is the first day of the week, and the second parameter is the number of days in the first week. Check the documentation for more details about how these fields affect the class behaviour.
To get the current date, you can use the LocalDate class:
// current date
LocalDate dt = LocalDate.now();
Then you make a loop that subtracts a certain number of weeks, and use the WeekFields to get the first and last day of each week. I also used a DateTimeFormatter to print the dates to same format of your output:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MMM", Locale.ENGLISH);
// get previous 4 weeks
for (int i = 4; i >= 1; i--) {
LocalDate pastWeek = dt.minusWeeks(i);
LocalDate startOfWeek = pastWeek.with(wf.dayOfWeek(), 1);
LocalDate endOfWeek = pastWeek.with(wf.dayOfWeek(), 7);
// you can add this String to your weekList
String week = startOfWeek.format(fmt) + " to " + endOfWeek.format(fmt);
System.out.println(week);
}
Output:
23-Feb to 01-Mar
02-Mar to 08-Mar
09-Mar to 15-Mar
16-Mar to 22-Mar

Related

Android on Gregorian Calendar

Guys I need help i want to display the month and date along with the day of following 7 days in format like
Sat - 22
Sun - 23
Mon - 24
..
Using a loop
what should be my approach within the loop ::
Calendar cal = new GregorianCalendar();
for(i = 0;i<7;i++)
{
int month = cal.get(Calendar.MONTH);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH + i); // Giving error here
day[i] = dayOfMonth + month + "";
}
I am totally a beginner in this field and im confused help me out
Changing:
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH + i);
to:
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH) + i;
Will fix the error.
But what you are trying to do can be better accomplished with:
Calendar cal = Calendar.getInstance();
for(i = 0; i < 7; i++) {
cal.add(Calendar.DAY_OF_MONTH, 1); // Adds a day to the date and takes care
// of adding month when its the last day of the month already
int weekDay = cal.get(Calendar.DAY_OF_WEEK); // Get weekday name like Sunday
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH)
day[i] = weekDay + " - " + dayOfMonth;
}

How to set start and end day(Date) of month using caldroid library?

How to Change start date and end date of month in calroid calendar lib if i want to modify calendar with shift my month start from 15 jan 2016 to 16 feb 2016.
Hello using following modification in CalendarHelper class you can set start date of month for shift calendar. I am using following library for calendar view https://github.com/roomorama/Caldroid
please modify getFullWeeks method
/**
* Retrieve all the dates for a given calendar month Include previous month,
* current month and next month.
*
* #param month
* #param year
* #param startDayOfWeek : calendar can start from customized date instead of Sunday
* #return
*/
public static ArrayList<DateTime> getFullWeeks(int month, int year, int startDayOfWeek,int startDayOfMonth, boolean sixWeeksInCalendar) {
ArrayList<DateTime> datetimeList = new ArrayList<DateTime>();
int dayCount=startDayOfMonth;
DateTime firstDateOfMonth = new DateTime(year, month, 1, 0, 0, 0, 0);
DateTime firstDateOfMonthToSet = new DateTime(year, month, dayCount, 0, 0, 0, 0);
int daysToAdd=firstDateOfMonth.getNumDaysInMonth()-dayCount;
DateTime lastDateOfMonth = firstDateOfMonthToSet.plusDays(daysToAdd);
DateTime lastDateOfMonthTpSet =firstDateOfMonthToSet.plusDays(firstDateOfMonth.getNumDaysInMonth()-1);
// Add dates of first week from previous month
// int weekdayOfFirstDate = firstDateOfMonth.getWeekDay();
//dr
int weekdayOfFirstDate = firstDateOfMonthToSet.getWeekDay();
// If weekdayOfFirstDate smaller than startDayOfWeek
// For e.g: weekdayFirstDate is Monday, startDayOfWeek is Tuesday
// increase the weekday of FirstDate because it's in the future
if (weekdayOfFirstDate < startDayOfWeek) {
weekdayOfFirstDate += 7;
}
while (weekdayOfFirstDate > 0) {
DateTime dateTime = firstDateOfMonthToSet.minusDays(weekdayOfFirstDate
- startDayOfWeek);
if (!dateTime.lt(firstDateOfMonthToSet)) {
break;
}
datetimeList.add(dateTime);
weekdayOfFirstDate--;
}
// Add dates of current month
for (int i = 0; i < lastDateOfMonth.getDay(); i++) {
datetimeList.add(firstDateOfMonthToSet.plusDays(i));
}
// Add dates of last week from next month
int endDayOfWeek = startDayOfWeek - 1;//dr
// int endDayOfWeek = startDayOfWeek;
if (endDayOfWeek == 0) {
endDayOfWeek = 7;
}
if (lastDateOfMonthTpSet.getWeekDay() != endDayOfWeek) {
int i = 1;
while (true) {
DateTime nextDay = lastDateOfMonthTpSet.plusDays(i);
datetimeList.add(nextDay);
i++;
if (nextDay.getWeekDay() == endDayOfWeek) {
break;
}
}
}
// Add more weeks to fill remaining rows
if (sixWeeksInCalendar) {
int size = datetimeList.size();
int row = size / 7;
int numOfDays = (6 - row) * 7;
DateTime lastDateTime = datetimeList.get(size - 1);
for (int i = 1; i <= numOfDays; i++) {
DateTime nextDateTime = lastDateTime.plusDays(i);
datetimeList.add(nextDateTime);
}
}
return datetimeList;
}
Hope this will help you :)

Error in adding recurrence event in Calendar

Hi I am tring to Create an app which add events to calendar. For example I need to create an event on every Saturday until dec 31ist.
The following are the attributes that I set for creating events,
event.put(CalendarContract.Events.CALENDAR_ID, 1);
event.put(CalendarContract.Events.TITLE, title);
event.put(CalendarContract.Events.DESCRIPTION, description);
event.put(CalendarContract.Events.EVENT_LOCATION, location);
event.put(CalendarContract.Events.DTSTART, sDate);
event.put(CalendarContract.Events.DURATION,"P50S");
event.put(CalendarContract.Events.ALL_DAY, 0);
event.put(CalendarContract.Events.HAS_ALARM, hasAlarm);
event.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone);
event.put(CalendarContract.Events.RRULE, "FREQ=WEEKLY;BYDAY=SA;UNTIL=20151230");
mContext.getContentResolver().insert(baseUri, event);
But it create an event for the given date (sDate) and then create every Saturday. But how can I avoid that one event which created on given date (sDate)
I had the same problem. You need to check your reccurrence rule for day of week and offset your DTSTART to the nearest Saturday (or any other weekday that your recurrence rule contains). To give you rough example how to do that I'm attaching code from Android Calendar app that offsets start time and end time of the event based on reccurence rule string, and returns two long values - new start time and new end time if offset was applied, or null if it wasn't. EventRecurrence class can be found via search on GrepCode, its part of Android calendar app
public static long[] offsetStartTimeIfNecessary(long startMilis, long endMilis, String rrule) {
if (rrule == null || rrule.isEmpty() || rrule.replace("RRULE:", "").isEmpty()) {
// No need to waste any time with the parsing if the rule is empty.
return null;
}
long result[] = new long[2];
Calendar startTime = Calendar.getInstance();
startTime.setTimeInMillis(startMilis);
Calendar endTime = Calendar.getInstance();
endTime.setTimeInMillis(endMilis);
EventRecurrence mEventRecurrence = new EventRecurrence();
mEventRecurrence.parse(rrule.replace("RRULE:", ""));
// Check if we meet the specific special case. It has to:
// * be weekly
// * not recur on the same day of the week that the startTime falls on
// In this case, we'll need to push the start time to fall on the first day of the week
// that is part of the recurrence.
if (mEventRecurrence.freq != EventRecurrence.WEEKLY) {
// Not weekly so nothing to worry about.
return null;
}
if (mEventRecurrence.byday == null ||
mEventRecurrence.byday.length > mEventRecurrence.bydayCount) {
// This shouldn't happen, but just in case something is weird about the recurrence.
return null;
}
// Start to figure out what the nearest weekday is.
int closestWeekday = Integer.MAX_VALUE;
int weekstart = EventRecurrence.day2TimeDay(mEventRecurrence.wkst);
int startDay = startTime.get(Calendar.DAY_OF_WEEK) - 1;
for (int i = 0; i < mEventRecurrence.bydayCount; i++) {
int day = EventRecurrence.day2TimeDay(mEventRecurrence.byday[i]);
if (day == startDay) {
// Our start day is one of the recurring days, so we're good.
return null;
}
if (day < weekstart) {
// Let's not make any assumptions about what weekstart can be.
day += 7;
}
// We either want the earliest day that is later in the week than startDay ...
if (day > startDay && (day < closestWeekday || closestWeekday < startDay)) {
closestWeekday = day;
}
// ... or if there are no days later than startDay, we want the earliest day that is
// earlier in the week than startDay.
if (closestWeekday == Integer.MAX_VALUE || closestWeekday < startDay) {
// We haven't found a day that's later in the week than startDay yet.
if (day < closestWeekday) {
closestWeekday = day;
}
}
}
if (closestWeekday < startDay) {
closestWeekday += 7;
}
int daysOffset = closestWeekday - startDay;
startTime.add(Calendar.DAY_OF_MONTH, daysOffset);
endTime.add(Calendar.DAY_OF_MONTH, daysOffset);
result[0] = startTime.getTimeInMillis();
result[1] = endTime.getTimeInMillis();
return result;
}

How to get list of dates inside the WEEK_OF_YEAR in android?

For example:
given month = 2, and given Year = 2014, i got the list of weeks using this following code. why i applied 1 for month is defaultly the month was start with index only.
SampleCode:
Calendar calendar = Calendar.getInstance();
calendar.set(1, 2014);
calendar.set(2014, 1, 1);
int ndays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
Set<Integer> weeks = new HashSet<Integer>();
for (int i = 1; i <= ndays; i++) {
weeks.add(calendar.get(Calendar.WEEK_OF_YEAR));
calendar.add(Calendar.DATE, 1);
}
Result:
weeks => [8, 9, 5, 6, 7]
After getting this result how can i get what are the dates are available with in the weekofyear. 2014 Febraury month, 5 th week having only one day (saturday). remaining weeks having sevendays except last 9th week.
I Expected Format:
week5 => 1-saturday
week6 => 2-sunday
3-monday
4-tuesday
5-wednesday
6-thursday
7-friday
8-saturday
week7 => 9-sunday
.
.
.
.
week9 => 23-sunday
24-monday
25-tuesday
26-wednesday
27-thursday
28-friday
29-saturday
some one guide me to get this List<Key,datelist> pair like above result.
why do you want to collect at first the weeks, and then find the days of the week.
As you are already looping over all days of a month, you could just create a map, which has the week as key and the list of days as value.
Somehow like that:
Calendar calendar = Calendar.getInstance();
calendar.set(1, 2014);
calendar.set(2014, 1, 1);
int ndays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
Map<Integer, List<Integer>> map = new TreeMap<Integer, List<Integer>>();
for (int i = 1; i <= ndays; i++) {
int week = calendar.get(Calendar.WEEK_OF_YEAR);
int day = calendar.get(Calendar.DAY_OF_MONTH);
List<Integer> dayList = map.get(week);
if (dayList == null) {
dayList = new ArrayList<Integer>();
map.put(week, dayList);
}
dayList.add(day);
calendar.add(Calendar.DATE, 1);
}
//Check the result:
for (Map.Entry<Integer, List<Integer>> entry : map.entrySet()) {
System.out.println("Week: " + entry.getKey());
for (int day : entry.getValue()) {
System.out.println("Day: " + day);
}
}

How to get the amount of passed time till now from a given unix timestamp

I am given a unix timestamp and I need to find the difference of seconds/min/hour by comparing with current time. I need something like:
34 sec ago
1 min ago
4 mins ago
5 hours ago
1 days ago
2 days ago
I have tried some poor if-else styled code but it is giving wrong wierd output
String time = null;
long quantity = 0;
long addition = 0;
long diffMSec = System.currentTimeMillis() - Long.parseLong(submissionInfo
.get(CommonUtils.KEY_SUBMISSION_TIME)) * 1000L;
diffMSec /= 1000L;
if (diffMSec < 86400L) { // less than one day
if (diffMSec < 3600L) { // less than one hour
if (diffMSec < 60L) { // less than one minute
quantity = diffMSec;
time = "sec ago";
} else { // greater than or equal to one minute
addition = (diffMSec % 60L) > 0 ? 1 : 0;
quantity = (diffMSec / 60L) + addition;
if (quantity > 1)
time = "mins ago";
else
time = "min ago";
}
} else { // greater than or equal to one hour
addition = (diffMSec % 3600L) > 0 ? 1 : 0;
quantity = (diffMSec / 3600L) + addition;
if (quantity > 1)
time = "hours ago";
else
time = "hour ago";
}
} else { // greater than or equal to one day
addition = (diffMSec % 86400) > 0 ? 1 : 0;
quantity = (diffMSec / 86400) + addition;
if (quantity > 1)
time = "days ago";
else
time = "1 day ago";
}
time = quantity + " " + time;
I need some working code with smarter approach or even any approach with working solution. Help me to figure it out.
I think you should use Calendar
Calendar cal = Calendar.getInstance();
String time = "yourtimestamp";
long timestampLong = Long.parseLong(time)*1000;
Date d = new Date(timestampLong);
Calendar c = Calendar.getInstance();
c.setTime(d);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
Calendar implements Comparable so ...
long subs = Math.abs(cal.getTimeInMillis() c.getTimeInMillis());
Calendar subCalendar = (Calendar)cal.clone();
subCalendar.setTimeInMillis(subs);
You can also use this link, because it seems to be a problem like yours

Categories

Resources