How to show progress based on days interval dynamically - android

I have to display progress bar based on day interval suppose that i have given start days and end days so we have to show progress in progress bar in such manner so that if you will 1-3 days then there should fill same progress 3 to 6 we should fill same progress ...and like this .
Given start date and end date based on that I have followed below steps
1 . find total number of days then
2 find days difference between todays date and start date
3 tried to get degree diff between today days and no of days left based one that I set mProgress.setProgress(degrees);.
private void displayProgressView() {
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.circular);
final ProgressBar mProgress = (ProgressBar) findViewById(R.id.circularProgressbar);
mProgress.setProgress(0); // Main Progress
mProgress.setSecondaryProgress(360); // Secondary Progress
mProgress.setMax(360); // Maximum Progress
mProgress.setProgressDrawable(drawable);
int noOfDaysLeft = noOfDaysLeft();
final int degrees = getDregeesFordays(totalDays() - noOfDaysLeft);
textView.setText(noOfDaysLeft() + "\nday" + (noOfDaysLeft() == 1 ? "" : "s"));
mProgress.setProgress(degrees);
}
here is date
"startDate": "2019-09-12T15:48:12.293Z",
"endDate": "2019-10-12T08:19:00.710Z",
i want to set progress based on multiple of 3 like if we have days diff is 1,2,3 then it should show same progress then 4,5,6 then it less secondly progress and so on ...

Get epoch time in unit of seconds. I use OffsetDateTime(ThreeTen).
val offset = OffsetDateTime.now().offset
val startDateEpoch = [your starting date in LocalDateTime unit].toEpochSecond(offset)
val endDateEpoch = [your end date in LocalDateTime unit].toEpochSecond(offset)
Calculate result = endDateEpoch - startDateEpoch
Translate it to days
eg. result = 500000
timeDifference = result / (3600 * 24)
... additional algorithm
Conditional check for progressBar
if(timeDifference >= 1 && timeDifference <= 3) doA()
else if(timeDifference >= 4 && timeDifference <= 7) doB()
...additional algorithm
Update : How to build LocalDateTime unit
val dayOfMonth = 23
val year = 2001
val month = 3
val hour = 0
val minute = 0
val myDate = LocalDate.of(year, month, dayOfMonth)
val myTime = LocalTime.of(hour, minute)
val startDateTime = LocalDateTime.of(myDate, myTime)

Related

Difference between two times in Android Studio, (Registered time and current time)

I have a simple code, I record the time when the user hits a button and subtract that time from the current time. It should give me the difference.
The funny part is that if I print my vars they are correct but when I make the subtraction the result is the year 1969 the time the system takes as reference.
This is my code:
// I register this time to later compare to the current time.
startTime = System.currentTimeMillis().toDouble()
timer = Timer()
timer.schedule(timerTask {
runOnUiThread {
advanceTimer()
}
}, 0, 60)
fun advanceTimer() {
//Total time since timer started, in seconds
val currentTime = System.currentTimeMillis().toDouble()
time = currentTime-startTime
}
This is what the console prints:
D/startTime: 2020:12:20:21:27:39:78
D/currentTime: 2020:12:20:21:29:49:21
D/time: 1969:12:31:18:02:09:42
Can somebody help me, please?
String time1 = "16:00:00";
String time2 = "19:00:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
This is how you calculate the time difference in Java.
The substraction of your date calculation is difference between two date
if you set to SimpleDateFormat date just show the difference of,
you can see at this answer https://stackoverflow.com/a/21285226/5523669
This answer lead me the right way, actually my approach was good I just needed to make a function that showed only the difference.
I made this one. Hope it helps somebody.
Just call the function with the result of you operation, at the end I used Date().getTime() instead of System.currentTimeMillis() but I think it should be the same.
The complete code:
startTime = System.currentTimeMillis().toDouble()
timer = Timer()
timer.schedule(timerTask {
runOnUiThread {
advanceTimer()
}
}, 0, 60)
fun advanceTimer() {
//Total time since timer started, in seconds
val currentTime = System.currentTimeMillis().toDouble()
time = currentTime-startTime
// Shows the time in a label on the screen
timerString.text = differenceResult(time)
}
fun differenceResult(time: Long): String {
var x: Long = time / 1000
var seconds = x % 60
x /= 60
var minutes = x % 60
x /= 60
var hours = (x % 24).toInt()
x /= 24
var days = x
return String.format("%02d:%02d:%02d", hours, minutes, seconds)
}

Struggle with parse function

So started learning Kotlin and Android studio coding.
I was following Youtube video
https://www.youtube.com/watch?v=z3_QgdmXGK4&t=994s&ab_channel=Dr.ParagShukla
I am making simple age calculator, however, cant make string to become date, so i could subtract input date with current date. Code looks exactly same as in the video.
Code compiles well and gets installed in android device, however, whenever press Calculate Age button, app stops responding because of var dob = sdf.parse(dob) function. I assume it cant convert the date from string to date format for further calculations. Thanks.
Code below:
fun openDatePicker(view: View) {
var c = Calendar.getInstance()
DatePickerDialog(
this,
DatePickerDialog.OnDateSetListener { datePicker, yy, mm, dd -> // listens what date picker has to say
var mm = mm + 1
var date = "$dd/ $mm /$yy "
TimePickerDialog(
this,
TimePickerDialog.OnTimeSetListener { timePicker, hh, mi ->
date += " $hh:$mi"
editTextTextPersonName.setText(date) // shows date in the line
},
c.get(Calendar.HOUR_OF_DAY),
c.get(Calendar.MINUTE),
true
).show()
}, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)
).show()
}
fun Calculateage(view: View) {
var today = Date() // todays date
var dobs = editTextTextPersonName.text.toString() // takes value from input
var sdf = SimpleDateFormat("mm/MM/yy HH:mm")
var dob = sdf.parse(dobs) // converts the date to simple date, no can find difference
var days = (today.time - dob.time) / 86400000 // converts into mil secs, need to divide by milsecs in a day
var hours = (today.time - dob.time) % 86400000 / 3600000
var minutes = (today.time - dob.time) % 86400000 % 3600000 / 60000
var sec = (today.time - dob.time) % 86400000 % 3600000 % 60000/1000
textView.visibility = View.VISIBLE
textView.setText("Days = $days\nHours= $hours\nMinutes=$minutes\nSeconds = $sec")
}
Your SimpleDateFormat doesn't match your string value.
Your var date looks like var date = "$dd/ $mm /$yy $hh:$mi"
Your SimpleDateFormat has "mm/MM/yy HH:mm"
You should change your formatter to something like this:
"dd/ MM /yy HH:mm"

Calculate remaining year,month and days from current date in android

I need to output the difference between 2 dates in years, months and days.
in my code when subtract two or three days from 1 year it gives wrong output
like remaining year,month,days is 0 year / 12 month /3 days
This is what I do.
Date date = null, date1 = null;
try {
date = formatter.parse(SharedPreference.getWeddingDate(getActivity()));
date1 = formatter.parse(getCurrentTimeStamp());
targetTime = new GregorianCalendar();
targetTime.setTime(date);
currentTime = new GregorianCalendar();
currentTime.setTime(date1);
}
catch (ParseException e) {
e.printStackTrace();
}
long timeOne = date.getTime();
long timeTwo = date1.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
int year = (int) (delta / 365);
int rest = (int) (delta % 365);
int month = rest / 30;
rest = rest % 30;
Unfortunately the stuff around java.util.Calendar does not give you any support for the calculation of durations. I know three external libraries available on Android platform which can do this much better and save you some headache. Internally the calculation is not so simple as some people want to make you believe. For example timezones are involved, too.
// input
String tz = "Europe/Paris";
java.util.Date d1 = new java.util.Date(0); // or: SharedPreference.getWeddingDate(getActivity());
java.util.Date d2 = new java.util.Date();
// library Threeten-ABP (similar but not identical to Java-8)
LocalDate start = Instant.ofEpochMilli(d1.getTime()).atZone(ZoneId.of(tz)).toLocalDate();
LocalDate end = Instant.ofEpochMilli(d2.getTime()).atZone(ZoneId.of(tz)).toLocalDate();
Period p = Period.between(start, end);
System.out.println(p.getYears()); // 45
System.out.println(p.getMonths()); // 11
System.out.println(p.getDays()); // 3
System.out.println(p); // P45Y11M3D
// Joda-Time-Android
DateTimeZone dtz = DateTimeZone.forID(tz);
org.joda.time.LocalDate jd1 = new org.joda.time.LocalDate(d1, dtz);
org.joda.time.LocalDate jd2 = new org.joda.time.LocalDate(d2, dtz);
org.joda.time.Period jp = new org.joda.time.Period(jd1, jd2, PeriodType.yearMonthDay());
System.out.println(jp.getYears()); // 45
System.out.println(jp.getMonths()); // 11
System.out.println(jp.getDays()); // 3
System.out.println(jp); // P45Y11M3D
// my library Time4A
PlainDate date1 = TemporalType.JAVA_UTIL_DATE.translate(d1).toZonalTimestamp(tz).toDate();
PlainDate date2 = TemporalType.JAVA_UTIL_DATE.translate(d2).toZonalTimestamp(tz).toDate();
Duration<CalendarUnit> duration = Duration.inYearsMonthsDays().between(date1, date2);
System.out.println(duration.getPartialAmount(CalendarUnit.YEARS)); // 45
System.out.println(duration.getPartialAmount(CalendarUnit.MONTHS)); // 11
System.out.println(duration.getPartialAmount(CalendarUnit.DAYS)); // 3
System.out.println(duration); // P45Y11M3D
If your wedding date input is in the future then just swap start and end in between-calculations in order to avoid negative durations.

Getting Time Until a Date in Android

I am using a Date and Time Dialog to get a Date and Time for an Event Specifed by the User. That data is the Converted by doing the following:
int yearE = Integer.valueOf(evntDate.split("/")[2]);
int monthE = Integer.valueOf(evntDate.split("/")[1]);
int dayE = Integer.valueOf(evntDate.split("/")[0]);
int hour = Integer.valueOf(evntTm.split(":")[0]);
int min = Integer.valueOf(evntTm.split(":")[1]);
With the Values of:
eventDate = "3/5/2015";
eventTime = "13:2";
I then get that data and COnvert it into Milliseconds and Store that in the Database:
newCalendar.set(yearE, monthE, dayE,hour, min, 0);
startTime = newCalendar.getTimeInMillis();
...
When I load the Info from the Database, I try to calculate the amount of time left until the Specified date. So I do the following:
Long timeL = Long.valueOf(time);
Calendar eventDay = Calendar.getInstance();
eventDay.setTimeInMillis(timeL);
Calendar today = Calendar.getInstance();
long diff = eventDay.getTimeInMillis() - today.getTimeInMillis();
// CONVERT:
int seconds = (int) TimeUnit.MILLISECONDS.toSeconds(diff);
int minutes = (int) TimeUnit.MILLISECONDS.toMinutes(diff);
int hours = (int) TimeUnit.MILLISECONDS.toHours(diff);
int days = (int) TimeUnit.MILLISECONDS.toDays(diff);
...
When I log the above data, the days are usually around 30-32 and the rest of the data is incorrect as well. What am I doing wrong? Or what are some alternatives?
Consider using the Joda time library instead of Calendar, it's much easier to work with.
As you're on android, I'll assume that you're using gradle, so go ahead and drop this in your dependencies
compile 'joda-time:joda-time:2.3'
I've created a small psvm to demo how you can use it
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.PeriodFormat;
import static java.lang.String.format;
public class DateTimeDemo {
public static void main(String[] args) {
// Your date/time values, I'll assume you missed a digit off the time ;)
String eventDate = "3/5/2015";
String eventTime = "13:20";
// convert these to a DateTime object
DateTime targetDateTime = DateTime.parse(format("%s %s", eventDate, eventTime), DateTimeFormat.forPattern("dd/MM/yyyy HH:mm"));
// print out the millis, or in your case, save it to DB
System.out.println("targetDateTime in millis is " + targetDateTime.getMillis());
// grab a timestamp
DateTime now = DateTime.now();
// print it out, just for demo
System.out.println("millis for now is " + now.getMillis());
// create a period object between the two
Period period = new Period(now, targetDateTime);
// print out each part
System.out.println("seconds " + period.getSeconds());
System.out.println("hours " + period.getHours());
System.out.println("months " + period.getMonths());
// convert the period to a printable String
String prettyPeriod = PeriodFormat.getDefault().print(period);
// write it out!
System.out.println(prettyPeriod);
}
}
Output is
targetDateTime in millis is 1430623200000
millis for now is 1425527593584
seconds 46
hours 22
months 1
1 month, 3 weeks, 6 days, 22 hours, 26 minutes, 46 seconds and 416 milliseconds
You can use Joda for that.
long dbTime = 1425525415837L;
Period period = new Period( dbTime, System.currentTimeMillis() );
String formatted = PeriodFormat.getDefault().print(period);
System.out.println( formatted );
If you want more control of the format use PeriodFormatter.
If you want to get the seconds, minutes, hours, etc. and not just print them, you can use the various available methods. For example:
period.getSeconds();
period.getHours();
period.getMonths();
More formatting options are described in this question.
Are you expecting to see something similar:
seconds = 36 (always less than 60)
minutes = 12 (always less that 60)
hours = 17 (always less than 24)
days = 45 (always less that 31 if # of months is used, else < 366 if # of years is used)
...
...
from:
// CONVERT:
int seconds = (int) TimeUnit.MILLISECONDS.toSeconds(diff);
int minutes = (int) TimeUnit.MILLISECONDS.toMinutes(diff);
int hours = (int) TimeUnit.MILLISECONDS.toHours(diff);
int days = (int) TimeUnit.MILLISECONDS.toDays(diff);
Its a logical error then. TimeUnit.MILLISECONDS.toXXXX(long) converts the whole time-difference into the specified units. This is of no value to you.
As an example, say you set the event's date to 32 days from now - and time to 13:15.
Millisecond difference =
2764800000 (32 days in millis)
+ 46800000 (13 hours in millis)
+ 900000 (15 minutes in millis)
= 2812500000
Using this time-difference, the following log:
int seconds = (int) TimeUnit.MILLISECONDS.toSeconds(diff);
int minutes = (int) TimeUnit.MILLISECONDS.toMinutes(diff);
int hours = (int) TimeUnit.MILLISECONDS.toHours(diff);
int days = (int) TimeUnit.MILLISECONDS.toDays(diff);
produces:
Seconds left: 2812500
Minutes left: 46875
Hours left: 781
Days left: 32
These figures are not off. A quick check would be: time difference in millis was: 2812500000 => in seconds would be diff/1000 = 2812500 => in minutes would be => diff/1000/60 = 46875 and so on.
Relative time:
To get relative time such as 32 days, 13 hours and 15 minutes left, you will have to do the heavy-lifting yourself. As an example:
// I will use the actual values instead of defined
// variables to make this easier to follow
long timeDiff = 2812500000L;
// Simple division // we don't care about the remainder
// Result: 32
int days = 2812500000 / DateUtils.DAY_IN_MILLIS;
// This is what's left over after we take the days out.
// We'll use this to get the number of hours.
// Result: 47700000
long remainderFromDays = 2812500000 % DateUtils.DAY_IN_MILLIS;
// Simple division // we don't care about the remainder
// Result: 13
int hours = 47700000 / DateUtils.HOUR_IN_MILLIS;
// This is what's left over after we take the hours out.
// We'll use this to get the number of minutes.
// Result: 900000
long remainderFromHours = 47700000 % DateUtils.HOUR_IN_MILLIS;
// Result: 15
int minutes = 900000 / DateUtils.MINUTE_IN_MILLIS;
// Result: 0
long remainderFromMinutes = 900000 % DateUtils.MINUTE_IN_MILLIS;
// Result: 0
int seconds = 0 / 1000; // 1000 ms = 1 sec
Log.i("Time-Difference", "Event in: " + String.format("Event in %d days, %d hours, %d minutes and %d seconds", days, hours, minutes, seconds));
Output:
Event in: 32 days, 13 hours, 15 minutes and 0 seconds
This is the very reason everyone here is suggesting Joda Time. The computation above is just off the top of my head. I cannot guarantee its correctness. If you also need relative month difference (such as 3 months, 2 days ....), a lot of work will be required. There isn't a DateUtils.MONTH_IN_MILLIS constant - varying number of days - 28, 29, 30, 31.
On the other hand, Joda Time is a tried & tested product. But, if all you need is one kind of computation, used scarcely (if ever), I'd say spend some time and come up with your own implementation rather than under-employ Joda Time.
Your code looks fine to me for what you are doing. Using org.joda.time as others have suggested is a best-practice, but it won't fix the problem. Instead you need to do two things:
Verify the Month that the user entered is in range (they may have entered the date in MM/DD/YYYY format). Month values greater than 12 won't throw an exception and your diff will be way off.
The line where you construct your date, subtract 1 from the month since months should be from 0 to 11, like:
newCalendar.set(yearE, monthE-1, dayE,hour, min, 0);

Change DateFormat depending on Days passsed

Essentially what I have is a string which contains a files Last Modified Date. To get this I'm using:
Date lastModDate = new Date(file.lastModified());
SimpleDateFormat formatter = new SimpleDateFormat("K:mm a");
String formattedDateString = formatter.format(lastModDate);
The end result is somewhat like 6:12 AM. What I want to do is each time a certain period of time is passed, the dateformat must change. E.g.
After 1 Day has gone by, Last Modified Date = ("Format1");
After a Week has gone by, Last Modified Date = ("Format2");
After 2 Weeks have gone by, Last Modified Date = ("Format3");
Does it make sense? If so is someone please be able to show me how it's done. A good example is the native Messaging App. When a message is created, It will show it's Time then after some days gone by the format changes to the Date it was created then the month etc...
I'm trying to do exactly that.
Calculate the difference in time between the last modified date and now:
long duration = lastModDate.getTimeInMillis() - current.getTimeInMillis();
long sec = TimeUnit.MILLISECONDS.toSeconds(duration);
boolean inFuture = sec > 0;
// Use positive value
if(!inFuture)
sec = -sec;
long minutes = sec / 60 % 60;
long hours = sec / 3600 % 24;
long days = sec / 86400;
if(days > 1 && days < 7)
// Use format 1
else if(days >= 7 && days < 14)
// Use format 2
else
// Use format 3

Categories

Resources