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;
}
Related
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
I want to make a countdown until a certain day but I don't know how to do it.
I want the countdown to count days, hours, minutes and seconds.
The final day will be set into the countdown with the format DAY/MONTH/YEAR. Ex: 11/9/15
Thank you and sorry for my English :P
EDIT:
What I want is the next:
You have a string that's a date (20/9/15). I want to make a countdown that counts DAYS, HOURS, MINUTES & SECONDS from today till the date. The countdown should be displayed on a textView
Thanks :D
Assuming you're using Java (you don't say), use the getTime method of the java.util.Date objects indicating now and then, get the difference between them to figure out the number of days, hours, minutes, etc... remaining.
public String timeRemaining(Date then) {
Date now = new Date();
long diff = then.getTime() - now.getTime();
String remaining = "";
if (diff >= 86400000) {
long days = diff / 86400000
remining += "" + days + (days > 1) ? "days" : "day";
diff -= days * 86400000;
}
//... similar math for hours, minutes
return remaining;
}
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);
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
i want to run an countdown time , in which i want to show days,hours,sec and milisec remaining for a specific date. and will be be keep changing till the end of the specific date.
Hope you can understand.
Thanks in advance.
Well, I think the problem is, that you dont know, how to work with the time. Here i have a method I use to calculate the amount of time of some items which I parse out of a db.
The param is a double value, which has got the whole time in seconds. It returns a string with the time in days, hours, minutes and seconds as string.
public String timeCalculate(double ttime) {
long days, hours, minutes, seconds;
String daysT = "", restT = "";
days = (Math.round(ttime) / 86400);
hours = (Math.round(ttime) / 3600) - (days * 24);
minutes = (Math.round(ttime) / 60) - (days * 1440) - (hours * 60);
seconds = Math.round(ttime) % 60;
if(days==1) daysT = String.format("%d day ", days);
if(days>1) daysT = String.format("%d days ", days);
restT = String.format("%02d:%02d:%02d", hours, minutes, seconds);
return daysT + restT;
}
For the countdown itself...take the target timestamp minus the actual one and voila, you've got seconds left :) Put those seconds to this method and you've got the remaining time. Now you just need to do some UI things ;)
Oh, and for the usual Unix Timestamp you can use this little method:
public static long getTimestamp() {
return System.currentTimeMillis() / 1000;
}