Getting Time Until a Date in Android - 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);

Related

Android - get Days, Months, and Years since a previous date

How in Android can I get and display the number of days, months, and years since a date?
For example, let's say the previous date is:
02/02/2017
and today's date is:
04/30/2018
I would want it to say something like:
1 year, 2 months, 28 days
I think I need to get total days like so:
long msDiff = Calendar.getInstance().getTimeInMillis() - oldCalendarDate.getTimeInMillis();
long daysDiff = TimeUnit.MILLISECONDS.toDays(msDiff);
but how do I convert the amount of days to be legible as years, months, and days? Keeping in mind that not all months have 31 days.
Because this way, I am only getting
452 days
As the result. But I want it to be more like 1 year, 2 months, 28 days.
Is there a better solution?
Also I want to get the old date like so in a variable:
val oldCalendarDate = GregorianCalendar(2017, 3, 30).time
but it's not working at all with the above code. Yes I'm aware that variable is in kotlin because I'm working in kotlin so pardon the syntax. I think the more issue about this is how the integers are formatted. I already converted the other java code to kotlin but I posted it as java for this post since more people are familiar with java.
Calendar Object can resolve this problem
val msDiff = Calendar.getInstance().timeInMillis - oldCalendarDate.timeInMillis;
val calDiff = Calendar.getInstance()
calDiff.timeInMillis = msDiff
val msg = "${calDiff.get(Calendar.YEAR) - 1970} year, ${calDiff.get(Calendar.MONTH)} months, $calDiff.get(Calendar.DAY_OF_MONTH)} days"
You try this code,
long different = your today date - your previous date;
// take both dates in date format.
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long mothsInMilli = daysInMilli * 30;
long yearInMilli = mothsInMilli * 12;
long elapsedYear = different / yearInMilli;
different = different % yearInMilli;
long diffYear = elapsedYear;
Log.d("", "difference of years : " + diffYear);
long elapsedMonths = different / mothsInMilli;
different = different % mothsInMilli;
long diffMonth = elapsedMonths;
Log.d("", "difference of Months : " + diffMonth);
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long diffDays = elapsedDays;
Log.d("", "difference of Days : " + diffDays);
Using this code I got proper difference, It may helps you also. Show below, I had two dates:
pastdate::Mon Mar 26 13:06:52 GMT+05:30 2018
todayDate::Mon Apr 30 13:06:52 GMT+05:30 2018
I got difference of month,year and days like below:-
difference of Years : 0
difference of Months : 1
difference of Days : 4

Difference between two Times in Minutes are coming as negative

I have a method which takes two String parameters. the two strings are Time values in 24 hour format. The Times are picked using a TimePicker from UI.
The goal of the method is to get the duration between the StartTime and EndTime in Minutes.
public static String getTimeDuration(String StartTime24, String EndTime24)
{
String duration = "";
try
{
SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm");
Date startTime = parseFormat.parse(StartTime24);
Date endTime = parseFormat.parse(EndTime24);
long mills = endTime.getTime() - startTime.getTime();
long minutes = mills/(1000 * 60);
duration = "(" + minutes + " Minutes)";
}
catch(ParseException ex)
{
// exception handling here
}
return duration;
}
The method works fine if both the times are within a Single Date. For example:
StartTime = 22:15
EndTime = 23:51
Output = (96 Minutes)
But my problem is, the method returns negative if the end time is after 12'o clock at night. For example,
StartTime = 23:51
EndTime = 0:55
Output = (-1376 Minutes)
What I want: (64 Minutes)
How can get the duration correct ?
As there is no date used, you have to check first if your endTime is less than your startTime. If yes, then your endTime is on the next day and you have to add 1 day/86 400 000 milliseconds. Then you will have your desired result.
Just add this condition:
if(endTime.getTime() < startTime.getTime()){
long mills = ((endTime.getTime() + 86400000) - startTime.getTime()); 1 day = 86 400 000 mill
}
Hope this helps
You're only parsing the minutes and hours. There's no day on there. So that puts both times on the same day (the first day of the epoch, Jan 1 1970 to be exact). So the answer is correct. If you want it to treat the end time as the next day if its earlier than the start time, then add 1 day to the result (1440 minutes) if the result is less than 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

Android: SimpleDateFormat keeps adding 1 hour to my time

I'm using currentTimeMillis(); to get a start time, then later using it again to get an end time. I then use delete start from end and get a value which is the duration between the two. I am using SimpleDateFormat to make all these values pretty and readable. the only thing is when i'm using a low value like 10 seconds (or 300 etc) and not the full blown long number (i.e. 1335718053126) I appear be getting out 01:00:10 or 01:02:12 etc on all my outputs? in fact if I just ask SimpleDateFormat to output a hh:mm:ss value against a 0 value it reads 01:00:00.
any one know why this is?
Found this neat little code if anyone else needs a solution to time formatting.
Source link
public String getNiceTime(long time) {
String format = String.format("%%0%dd", 2);
String seconds = String.format(format, time % 60);
String minutes = String.format(format, (time % 3600) / 60);
String hours = String.format(format, time / 3600);
String outPutTime = hours + ":" + minutes + ":" + seconds;
return outPutTime;
}
mySimpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Explanation: you are probably living in a GMT+1 time zone and unless you specify a different one, your formatter will pick your current one, so it considers 0 hours as GMT and as you are in GMT+1, it outputs 1 hour

Counting dates on Android

Well i'm currently building an app for android and i need to store a day and count how many days until that day comes.
I store the day on shared prefs. First i initialize the calendars.
Calendar next = Calendar.getInstance();
Calendar now = Calendar.getInstance();
Then i set the "next" calendar
nday = prefs.getInt("d", 0);
nmonth = prefs.getInt("m",0);
nyear = prefs.getInt("y",0);
next.set(nyear, nmonth, nday);
Then i do this to calculate how many days left.
diff =next.getTimeInMillis()-now.getTimeInMillis();
diffDays = diff / (24 * 60 * 60 * 1000);
output.setText(diffDays + " Days left");
And here is the problem. The calculator was working great until 2 days ago. When it supposed to say "3 days" it was writing "2 days" and it still goes one day wrong. If i try close and open the app, sometimes it calculates the days correct and sometimes it misses one day... Can someone understands whats wrong? I have diff and diffDays as long. I tried cast them as int but i still got the same problem, sometimes it writes 3 days left, sometimes 2....
ok i found out how to solve this. It seems that the getInstance have difference in milliseconds so i did this
Calendar now = Calendar.getInstance();
now.set(Calendar.HOUR_OF_DAY,00);
now.set(Calendar.MINUTE ,00);
now.set(Calendar.SECOND,00);
now.set(Calendar.MILLISECOND,00);
get the day from shared prefs
nday = extras.getInt("nDay");
nmonth = extras.getInt("nMonth");
nyear = extras.getInt("nYear");
//set the calendar
next.set(nyear, nmonth, nday, 00, 00,00);
next.set(Calendar.MILLISECOND,00);
and finally calculate the difference
long diff = 0;
diff = next.getTimeInMillis()-now.getTimeInMillis();
diffDays = diff / (24 * 60 * 60 * 1000);
output.setText(diffDays + " Days");
now i get the real difference without any mistakes, thanks everyone for your help!
Because it is implicitly casting to long, so you are losing some of your minutes and hours.
Declare diffDays as double, then you can show to the user when there are, for example 2.5 days and it won't show it as 2 days. Or, you could take the integer part for the days, and calculate the hour from the fraction:
int hour = (diffDays - Math.floor(diffDays))*24
This gives you the minute. Just make sure you did declare diffDays as double or float.
Also use the calendar for calculating dates.
Calendar diff = Calendar.getInstance();
long diffMillis = next.getTimeInMillis()-now.getTimeInMillis();
diff.setTimeInMilliSeconds(Math.abs(diffMillis));
int days = diff.get(Calendar.DAY_OF_YEAR);
if (diffMillis < 0L) {
days *= -1;
}

Categories

Resources