Get Week from given Calendar Range? - android

I am implementing an application where I have two calendar object with minimum and maximum date range.
Is there a way to get total week count
How can get week information based on index say: need 5th week of calendar range
any one have suggestion here ?

As mentioned here Get the number of weeks between two Dates. maybe you can use JodaTime http://www.joda.org/joda-time/
android version https://github.com/dlew/joda-time-android
DateTime dateTime1 = new DateTime(date1);
DateTime dateTime2 = new DateTime(date2);
int weeks = Weeks.weeksBetween(dateTime1, dateTime2).getWeeks();

Related

Difference between 2 dates in days and in double

I am working on an app and i need to get the difference between the actual date and a date inserted by the user, in days and in double.
Any idea on how to make this? I've tried some things but without success.
First you must decide if you want to consider the time of the day and the timezone to calculate the difference, because this can lead to different results.
Example: current date (AKA "today") is April 17th or 18th, depending on where in the world you are. Actually, depending on the time of the day, there might be 3 different "todays" in the world, at the same time. What timezone are you using to calculate the difference?
the user will enter a date: only day, month and year? Will it enter the hours? Are you using the user's device's timezone or some specific zone?
the same questions apply to the current date
Depending on the choices you make, you might get a different result.
Anyway, I'd use this lib: http://www.threeten.org/threetenbp/
or java.time classes, if available in your API level. In both API's you can use the following.
To use a date (day-month-year only) and the device's default timezone, I'd choose the LocalDate class:
// current date in device's default timezone
LocalDate now = LocalDate.now();
// some date from input values (May 10th 2018)
LocalDate dt = LocalDate.of(2018, 5, 10);
// difference in days
long diff = ChronoUnit.DAYS.between(now, dt); // 23
If you want to consider the time of the day (hours, minutes, etc), use a LocalDateTime. But in this case, ChronoUnit.DAYS considers a day has passed when the time is >= the other (ex: the difference between April 17th at 10 AM and April 18th 9:59 AM is zero days, because the time of the day didn't reach 10 AM, so it didn't complete 1 day - with LocalDate this doesn't happen because this class doesn't have time-of-the-day fields and considers only the day, month and year).
If you want to consider everything (date, time, and timezone), including Daylight Saving Time transitions, use a ZonedDateTime instead (the code is very similar, the only difference is that you can choose a timezone to work with):
// current date/time in device's default timezone
ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
// some date from input values (May 10th 2018, 10 AM in New York timezone)
ZonedDateTime dt = ZonedDateTime.of(2018, 5, 10, 10, 0, 0, 0, ZoneId.of("America/New_York"));
// difference in days
long diff = ChronoUnit.DAYS.between(now, dt); // 23
You can choose between the device's default timezone (ZoneId.systemDefault()) or a specific one (ZoneId.of("America/New_York")). You can check all the available timezones with ZoneId.getAvailableZoneIds().
Maybe it doesn't make sense to use current date in one timezone and user's date in another (I'd use the same for both), but that's up to you to decide.
Calendar c = Calendar.getInstance();
Calendar c2 // = what you will get from the user
long diff = c.getTimeInMillis()-c2.
double days = (double) diff/(1000*60*60*24);
that is what i have in mind.
I hope this helps
use this way
public static double getTimeDiffBetweenDate(Date startDateTime, Date finishDateTime) {
long diffInMilliseconds = finishDateTime.getTime() - startDateTime.getTime();
return TimeUnit.MILLISECONDS.toMinutes(diffInMilliseconds) / 60.0;
}

How to get all previous weeks

How to get all weeks of month with date,I am doing like this
calendar.add(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek() - calendar.get(Calendar.DAY_OF_WEEK));
String[] weekly = new String[7];
Arrays.fill(weekly, "");
int today = calendar.getInstance().get(Calendar.DAY_OF_WEEK);
for (int i = 0; i < 7; i++) {
Date dt = calendar.getTime ();
// now format it using SimpleDateFormat
DateFormat df = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
String val = df.format (dt);
weekly[i] = val;
calendar.add (Calendar.DAY_OF_WEEK, 2);
Log.d("valueweek",""+weekly[i]);
}
output
26-11-2017
27-11-2017
28-11-2017
29-11-2017
30-11-2017
01-12-2017
02-12-2017
But i also want all previous weeks of this month
java.time
First, do consider to drop the long outmoded classes Calendar, Date and DateFormat. Today we have so much better in java.time, the modern Java date and time API also known as JSR-310. On Android too, I will return to that. The modern API is so much nicer to work with.
If I understand your request correctly, this should give you what you want:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
WeekFields localWeekFields = WeekFields.of(Locale.getDefault());
LocalDate today = LocalDate.now(ZoneId.of("Europe/Helsinki"));
Month thisMonth = today.getMonth();
LocalDate weekStart = today.withDayOfMonth(1)
.with(TemporalAdjusters.previousOrSame(localWeekFields.getFirstDayOfWeek()));
// Iterate over weeks
do {
System.out.println("Here’s a week:");
// Iterate over days in week
LocalDate day = weekStart;
for (int i = 0; i < 7; i++) {
System.out.println(day.format(dateFormatter));
day = day.plusDays(1);
}
weekStart = weekStart.plusWeeks(1);
} while (weekStart.getMonth().equals(thisMonth));
Running this snippet on my computer today it prints the days of 5 weeks, so I will only show you the first and the last lines of output:
Here’s a week:
30-10-2017
31-10-2017
01-11-2017
02-11-2017
…
Here’s a week:
27-11-2017
28-11-2017
29-11-2017
30-11-2017
01-12-2017
02-12-2017
03-12-2017
Since in my locale the week starts on Monday, the above weeks go from Monday to Sunday. If you run the same code in a locale where Sunday is the first day of the week, they should go from Sunday to Saturday.
A little explanation: WeekFields.of(Locale.getDefault()) gives us a WeekFields object of the current locale. We use this a few lines down to determine the first day of the week. Then we query today’s date in your desired time zone — please fill the desired time zone in if you don’t want Europe/Helsinki. To iterate over the weeks, we initialize a LocalDate to the first day of the first week by first finding the first day of this month and then going back to the first day of the week (possibly going into the previous month). To determine which is the first day of the week, we query the WeekFields object that we got a few lines earlier as the one belonging to the current locale (you can fill in a different locale if desired, or just a different WeekFields object).
In the loop over weeks we first print the week and then add one week to weekStart, so we’re ready for next week. The loop condition is that we’re within the current month. To make sure the loop makes its first iteration even if we started on one of the last days of the previous month, I use a do-while loop rather than a while loop.
Will this work on Android?
You certainly can use the modern API on Android too. You need to get ThreeTenABP, the backport of the modern API to Android (that’s ThreeTen for JSR-310 and ABP for Android Backport). It’s all well and thoroughly explained in this question: How to use ThreeTenABP in Android Project.

Compare current date with stored one

For an easteregg in my Android app, I have to compare the current date with a stored date - and I only need to know if it's the right month.
I know that System.currentTimeMillis() is the fastest way to get the current time but now I need to get the current month from that. I avoided String comparison for it's known flaws.
My awful implementation works but it really doesn't look correct and efficient:
if (Integer.parseInt((String) DateFormat.format("MM",System.currentTimeMillis()))==12) //xmas "easteregg"
xmasBool=true;
Is there any more elegant solution for this?
Here's a better solution:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date()); // Date's default constructor gives you current time
xmasBool = calendar.get(Calendar.MONTH) == Calendar.DECEMBER;
Calendar c = Calendar.getInstance();
int month = c.get(Calendar.MONTH);
And now you can compare the variable month with your stored month.
You can compare a day or a month or both, the whole date by formatting java.Util.Date using SimpleDateFormat.
Eg.
new SimpleDateFormat("dd").format(new java.util.Date())
gives you the "day" value. Similarly "MM" will give you the month. Use combination of those as per your requirement.
Store it in the same format and you have a common standard for comparison.

Joda library does not work properly

I'm using Joda library in my android application to calculate the duration between two given dates. Using this application to calculate a person's age.
The following code gives this output : 23 years 11 months and 6 days
DateTime from_readable_dateTime = new DateTime(from_date_dt);
DateTime to_readable_dateTime = new DateTime(to_date_dt);
Period period = new Period(from_readable_dateTime, to_readable_dateTime);
from_date_dt in this case is 1990/01/06 and to_date_dt is 2014/09/15. (date format is yyyy/mm/dd). As I mentioned earlier the output of this piece of code with the given inputs must be 24 years, 7 months and 20 days while I get 23 years 11 months and 6 days. What's the problem? Am I doing something wrong or Joda is faulty?
UPDATE-1
I get 3 numbers as year, month and day from 3 number pickers I make a single string as date(start date variable is named from_date_string and end date is named to_date_string), I convert these two strings to date variables (from_date_dt and to_date_dt):
from_date_dt = null;
to_date_dt = null;
diff_dt = null;
dateFormat = new SimpleDateFormat("yyyy/mm/dd");
try {
from_date_dt = dateFormat.parse(from_date_string);
to_date_dt = dateFormat.parse(to_date_string);
} catch (ParseException e) {
e.printStackTrace();
}
BTW, I'm working with Persian calendar. Since I can't use the default date picker, I'm using number pickers as date pickers.
The standard period type which you implicitly use contains weeks. The class Period has another constructor with 3 arguments where you can specify PeriodType.yearMonthDay() as third argument.
LocalDate d1 = new LocalDate(1990, 1, 6);
LocalDate d2 = new LocalDate(2014, 9, 15);
Period p = new Period(d1, d2, PeriodType.yearMonthDay());
System.out.println(p); // output: P24Y8M9D
To explain the result in fine-granular steps:
[1990-01-06] + 24 years = [2014-01-06]
[2014-01-06] + 8 months = [2014-09-06]
[2014-09-06] + 9 days = [2014-09-15]
Another thing to consider, don't use DateTime if your input is just a plain date format. Do you really want to take into account timezone effects? And why do you use SimpleDateFormat although JodaTime has its own formatters?
UPDATE after updated question of OP:
Now the question has become a lot clearer.
First to note generally, if you use number pickers then your original input for year, month and day-of-month are just integers. In that case I would normally not use a formatter at all, but just pass the numbers to the constructor of LocalDate. This constructor will also verify the input automatically. The complex conversion you try is very error-prone (number to string, then string concatenation to a date string, then parsing it with your default timezone and then passing java.util.Date to DateTime-ctor). It can be completely avoided.
Second to note and most important: You write that you use a persian calendar. Then the reason why you cannot use the default date picker is simply that this default date picker does not support the calendrical rules of persian calendar. Is my speculation right? And here the very bad news for you: Jodas classes do NOT support the persian calendar, too, especially LocalDate or DateTime are only designed for the ISO-8601-standard which is based on the modern proleptic gregorian calendar. Month lengths for example are different in gregorian calendar and in persian calendar, hence a completely different calendar arithmetic is required which is not supported by Joda-Time.
So your strange period results are probably explainable by the fact that you tried to let the user define persian year, month and day. And then you try to parse this input leniently (otherwise Joda-Time would immediately complain about odd day-values for example). But the last step - period calculation - must fail because it is based on ISO-8601 in Joda-Time and not persian calendar rules.
Am I right? Or have I misinterpreted your updated question?
A work-around is difficult. If you really want to have period calculation for a persian calendar then you have to build it from the scratch. As far as I know there is actually no library which supports this feature. A guideline for writing a persian solution can be the algorithm discussed in this SO-post however.
UPDATE indicating a solution:
Meanwhile I have implemented the Persian calendar in Time4A, see also this SO-post. So if you are able to use Time4A and combine the PersianCalendar with the algorithm for a multi-unit-period mentioned above then this will solve your problem. Time4A-v3.15-2016a explicitly supports special Persian calendar units which use different rules than gregorian calendar units.

How to calculate the total number of days passed [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculate date/time difference in java
I am providing the user with the option to select the date using Date Picker. Is there any in-built method using which I can calculate the duration in days wrt to user selected date and todays date.
I don't like answering this because there were millions of questions like this (use search option before posting questions). Use Joda Time. There is a Period class, which will be useful for you.
Get the difference between the two times in milliseconds. Than you can get the Days via Java's Calendar class.
Date today = new Date(); // the date of today
Date target = new Date(); // the date of when the user picks
long todayEpoch = today.getTime(); // or can use = System.currentTimeMillis();
long targetEpoch = target.getTime();
long daysInMs = targetEpoch - todayEpoch; //days in MS's
//the # of days
float days = (daysInMs/1000/60/60/12);

Categories

Resources