Joda Time on Android not computing correctly - android

So, I am trying to computer the difference between two dates in time, and out puting that difference in days, hours, and minutes. I've been running this sample code just as a java console application and it works fine, however, when I try to do the same thing in Android, I get garbage data. Is Joda Time too complex for Android? Should I try out Date4j as an alternative?
import java.util.; import org.joda.;
import org.joda.time.DateTime;
public class time {
//(5000);
final static long MILLIS_IN_DAY = 86400000;
final static long MILLIS_IN_HOUR = 3600000;
final static long MILLIS_IN_MINUTE = 60000;
public static void main(String[] args){
long day, hour, minute;
//MAKE SURE TO CHECK IF USER SET(LATER)
// DateTime(2013,9,12,0,0)
DateTime d1 = new DateTime(2013,9,17,0,0);
DateTime d2 = new DateTime(2013,9,12,21,30);
//long date = d2.getMillis();
DateTime d3 = new DateTime();
long diffInMillis = d3.getMillis() - d1.getMillis();
minute = (diffInMillis/MILLIS_IN_MINUTE)%60;
hour = (diffInMillis/MILLIS_IN_HOUR)%24;
day = (diffInMillis/MILLIS_IN_DAY);
System.out.println(Long.toString(d1.getMillis()));
System.out.println(Long.toString(d2.getMillis()));
System.out.println(Long.toString(d3.getMillis()));
System.out.println(Long.toString(diffInMillis));
System.out.println("Minutes:");
System.out.println(Long.toString(minute));
System.out.println("Hours:");
System.out.println(Long.toString(hour));
System.out.println("Days:");
System.out.println(Long.toString(day));
}
}

Don't calculate this values manually. Calculate with Joda-Time methods. There is no reason to use Joda and don't use Joda's methods
E.g.
with Days, Hours, Mintes
System.out.println("Minutes:");
System.out.println(Minutes.minutesBetween(d2, d1).getMinutes() % 60);
System.out.println("Hours:");
System.out.println(Hours.hoursBetween(d2, d1).getHours() % 24);
System.out.println("Days:");
System.out.println(Days.daysBetween(d2, d1).getDays());
or with Period
Period period = new Period(d2, d1);
System.out.println("Minutes:");
System.out.println(period.getMinutes());
System.out.println("Hours:");
System.out.println(period.getHours());
System.out.println("Days:");
System.out.println(period.getDays());

Related

Get a random time between two time

Time 1 : 10:30 06/05/2018
Time 2 : 19:45 06/05 2018
I want to pick a random time between these two time. The result may be (13:15 06/05/2018).
I look into Calendar but seem it does not support a method like range(time1, time2)
What is the solution for this case ? Thanks.
I would use something like this.
public static Calendar getRandomTime(Calendar begin, Calendar end){
Random rnd = new Random();
long min = begin.getTimeInMillis();
long max = end.getTimeInMillis();
long randomNum = min + rnd.nextLong()%(max - min + 1);
Calendar res = Calendar.getInstance();
res.setTimeInMillis(randomNum);
return res;
}
if you have API 21+, use ThreadLocalRandom
public static Calendar getRandomTime(Calendar begin, Calendar end){
long randomNum = ThreadLocalRandom.current().nextLong(begin.getTimeInMillis(), end.getTimeInMillis() + 1);
Calendar res = Calendar.getInstance();
res.setTimeInMillis(randomNum);
return res;
}
you should convert your times objects to long first as follows (I suppose that you have two Calendar objects already)
long time1InLong = time1.getTimeInMillis();
long time2InLong = time2.getTimeInMillis();
Then you can use following code to generate random number
Random r = new Random();
long randomTime = r.nextLong(time2InLong - time1InLong) + time1InLong;
Then you can convert this randomTime back to Calendar as follows
// Create a DateFormatter object for displaying date in specified format.
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm dd/MM/yyyy");
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(randomTime);

how to get correct date diffrence

i want to compare a date with the current date and do something if the difference is 2 months or 6 or a year .. but i have a problem how to get the correct difference for example if the current month is 02 2015 and the other month is 10 2014 i will get 8 in difference but the actual difference is 4 .. how to do it ?
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat d = new SimpleDateFormat("dd");
SimpleDateFormat m = new SimpleDateFormat("MM");
SimpleDateFormat ye = new SimpleDateFormat("yyyy");
String day = d.format(c.getTime());
String month = m.format(c.getTime());
String year = ye.format(c.getTime());
int d1=Integer.parseInt(day);
int m1=Integer.parseInt(month);
int d2=25;
int m2=02;
int diff=d1-d2;
String s=String.valueOf(diff);
You are calculating your difference between two int, so it can't work.
You should calculate it between two dates or two long (in secondes or milliseconds)
long oneDay, today, delay;
oneDay = 1000*3600*24; //number of milliseconds in a day
today = Calendar.getInstance().getTimeInMillis();
delay = (TheDateYouWantToCompare - today)/oneDay;
if (delay >= 60*oneDay) { //more than 2 months
//your code
}else{
//your code
}
If TheDateYouWantToCompare and today are dates, it's almost the same :
delay = (TheDateYouWantToCompare.getTime() - today.getTime())/oneDay;
Edit :
Here it is how to get time in milliseconds.
String DateString = "31-12-2015";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date myDate = sdf.parse(DateString);
long timeInMilliseconds = myDate.getTime();
You could just use the difference in milliseconds between the 2 dates. Pre-compute the differences you need/want as constants and compare to the delta you have, for example:
static final long DAY = 1000 * 60 * 60 * 25;
static final long MONTH = DAY * 30;
...
int diff = d1 - d2;
if(diff > MONTH) {
//more than a month difference
}
If you need something more complex you should perhaps use a library such as Joda Time which will give a more comprehensive set of features to work with time.

How to get the Time like facebook post eg. 1sec ago or 3hrs ago, In android application

I have developed an application where the user receives the message from other application user. I want to just show the time like Facebook, eg. 1sec ago or 3Hrs ago. Something in this fashion. I tried a code from one of our Fellow S.O expert but that code seems to misbehave.
Here's the code which i used in my app.
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
static int[] steps = { 1, 60, 3600, 3600 * 24 };
static String[] names = { "sec", "mins", "hrs", "days" };
public static String formatDelay(String date) {
try {
Date d = sdf.parse(date);
Long stamp = d.getTime();
Calendar c = Calendar.getInstance();
Long now = System.currentTimeMillis() / 1000;
Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
String time = format.format(now);
Long dif = now - stamp;
dif = dif / 1000;
if (stamp > now)
return "";
for (int i = 0; i < steps.length; i++) {
if (dif < steps[i]) {
String output = Long.toString(dif / steps[i - 1]) + " "
+ names[i - 1];
return output;
}
}
return Long.toString(dif / steps[3]) + " " + names[3];
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
When I used this code and sent a message from my application , it should show me sent 1sec ago, but in my case it shows me wrong time delay. For eg. I sent the message at 6pm then when I check my application sent item at 6:15pm its should show me 15 mins ago. But it shows me 12 hrs. When i debugged code, got to know that now time show date as 1970 00:00:00, this is because Long now = System.currentTimeMillis() / 1000; when i remove that /1000 it shows me correct date and time. I am clue less why this is happening please help.
Use
android.text.format.DateUtils.getRelativeTimeSpanString (long time, long now, long minResolution, int flags)
this will return time span in String format
For eg. if you pass a long value corresponding to 42 minutes ago in time and flags as DateUtils.FORMAT_ABBREV_RELATIVE the method will return 42 minutes ago
Official documentation DateUtils.getRelativeTimeSpanString
When you divide System.currentTimeMillis() by 1000 you are converting its value to seconds.
You're then using that value to create a date which is interpreting the seconds value as the milliseconds since Thu Jan 01 1970, hence the date difference.
I would recommend using Joda-Time API. See this answer for reference.

How to compare two timestamps in android?

I want to compare two timestamps and if the difference of that is (-+5minuts) then I want to display alert dialog.
i.e. If currently in our watch 4PM the second time is 4.05PM or 3.55PM then alert will display else not.
Can anyone suggest me the way how can I get the solution of this.??
I found after search the function of getting timeStamp and how to compare two timestamps but for this type of condition is there any method or function?
Thanks.
My code is:-
date= new Date();
currentTime = date.getTime();
if(currentTime !=0 && previousTime !=0){
String result = (String) DateUtils.getRelativeTimeSpanString(currentTime, previousTime, 0);
}
And I am storeing current time in to previous time lilke tis way :-
if(currentTime != previousTime){
previousTime = currentTime;
}
There's two approaches you could take, depending on whether you just want to measure time elapsed, or want to set future times to compare to.
The first is similar to Sourabh Saldi's answer, record the result from
long prevEventTime = System.currentTimeMillis();
then compare it with System.currentTimeMillis() until the difference is more than 300000
As you have mentioned, your timestamp from the server is in milliseconds since January the 1st, 1970. This means it is directly comparable to System.currentTimeMillis(). As such, use:
long serverTimeStamp=//whatever your server timestamp is, however you are getting it.
//You may have to use Long.parseLong(serverTimestampString) to convert it from a string
//3000(millliseconds in a second)*60(seconds in a minute)*5(number of minutes)=300000
if (Math.abs(serverTimeStamp-System.currentTimeMillis())>300000){
//server timestamp is within 5 minutes of current system time
} else {
//server is not within 5 minutes of current system time
}
The other method looks closer to what you're already doing - using the Date class to store the current and compared time. To use these, you'll want to be using the GregorianCalendar class to handle them. Calling
calendar=new GregorianCalendar();
will create a new calendar, and automatically set it's date to the current system time. You can also use all the functions supplied in the GregorianCalendar class to roll the time forward or backward using something of the form
calendar.add(GregorianCalendar.MINUTE, 5);
or set it to a Date object's time with
calendar.setTime(date);
In your case, depending on how much flexibility you want both the GregorianCalendar class and the Date class have after() methods, so you probably want something like the following:
Create somewhere:
Date currentDate=newDate();
Then set your alarm point:
calendar=new GregorianCalendar(); //this initialises to the current system time
calendar.setTimeInMillis(<server timestamp>); //change to whatever the long timestamp value from your server is
calendar.add(GregorianCalendar.MINUTE, 5); //set a time 5 minutes after the timestamp
Date beforeThisDate = calendar.getTime();
calendar.add(GregorianCalendar.MINUTE, -10); //set a time 5 minutes before the timestamp
Date afterThisDate = calendar.getTime();
Then check if the current time is past the set alarm point with
currentDate.setTime(System.currentTimeMillis());
if ((currentDate.before(beforeThisDate))&&(currentDate.after(afterThisDate))){
//do stuff, current time is within the two dates (5 mins either side of the server timestamp)
} else {
//current time is not within the two dates
}
This approach can seem a bit more long winded, but you'll find it is very robust and flexible, and can easily be extended to set alarm points far in the future, or use the GregorianCalendar methods to easily set dates hours, days or weeks into the future.
How about just:
private static final long FIVE_MINUTES = 1000 * 60 * 5; //5 minutes in milliseconds
long currentTime = new Date().getTime();
long previousTime = mPreviousTime;
long differ = (currentTime - previousTime);
if (differ < FIVE_MINUTES && differ > -FIVE_MINUTES ){
// under +/-5 minutes, do the work
}else{
// over 5 minutes
}
long etime = 0;
final long time1 = uptimeMillis();
/* do something */
final long time2 = uptimeMillis();
if (time2 < time1) {
etime = Long.MAX_VALUE - time1 + time2;
} else {
etime = time2 - time1;
}
then check this etime and do as required!!1
Use this following method to change your dates in epoch format
public Long getChnagedDate(Activity act,String date) throws ParseException
{
long epoch = new java.text.SimpleDateFormat ("MM/dd/yyyy HH:mm:ss aa").parse(date).getTime();
return epoch/1000;
}
and after check the difference in http://www.epochconverter.com.
Hope it helps you.
Joda time will help you with this task.
import org.joda.time.Interval;
http://joda-time.sourceforge.net/

Add a certain amount of time to a current time and write it

I'm using:
Calendar c = Calendar.getInstance();
with which i get a current time,
String sHour = c.get(Calendar.HOUR_OF_DAY)
String sMinute = c.get(Calendar.MINUTE)
What i need is to add e.g. 1 Hour 10 Minutes - store it in a variable and also Substract let's say 10 minutes and save that as an another variable. (I need to use them both in a TextView)
I've seen the add(); method in Android documentation but I can't seem to understand how it works. Thanks
The code you've posted won't compile, as Calendar.get() doesn't return a string. You should also note that calendar is mutable - it's not like each call to add returns a new calendar. So you'll need to create a new instance each time you want a separate variable for a different value. For example:
Calendar now = Calendar.getInstance();
Calendar tmp = (Calendar) now.clone();
tmp.add(Calendar.HOUR_OF_DAY, 1);
tmp.add(Calendar.MINUTE, 10);
Calendar nowPlus70Minutes = tmp;
tmp = (Calendar) now.clone();
tmp.add(Calendar.MINUTE, -10);
Calendar nowMinus10Minutes = tmp;
If at all possible, I'd strongly recommend that you use Joda Time instead of Calendar/Date - it's a far superior API. You may want to trim the time zones included with it, however, so that it's faster to get started and less overhead in your apk.
You can simply call System.currentTimeMillis() + INTERVAL.
Where INTERVAL is the interval in milliseconds (for example:
public static final long INTERVAL = 1000 * 60 * 60 * 24; // 1 day

Categories

Resources