android time calculator example code (help) - android

I am a little bit confused by the date formatter/calander and all the formats that are related to the time. I am trying to get the current time with no date and, although I have seen several code snippets this still confuses me.
My problem is the following is to get current time and send it to some method for some calculations.
For example
public void onCreate(Bundle savedInstanceState){....
.........
........
**get the current time**
sendToMethod(currentTime)
}
public void sendToMethod(currentTime)
{
Date pastTime
long diff = currentTime - pastTime;
if (diff > 1000) // here i want to check if the diffrence is more then 10 seconds
// do something
}
I searched and tried several codes but I got lost.
I found that there are alot of ways to do this, but I still have no clue how to solve this.
Please, if anyone can help me I will appreciate it a lot.

Try this:
private long diff, start = System.currentTimeMillis();
public void sendToMethod()
{
diff = System.currentTimeMillis() - start;
if (diff > 10000) { // difference is more then 10 seconds
// do something
}
start = System.currentTimeMillis();
}

You can try using Joda time.
No Joda time:
Calendar c = Calendar.getInstance();
int seconds/minutes/hours/etc = c.get(Calendar.SECOND/MINUTE/HOUR/etc);
In Joda Time:
DateTime dt = new DateTime(DateTimeZone.UTC);
int month = dt.getMonthOfYear();
// where January is 1 and December is 12
int year = dt.getYear();
Edit
If you want to get the current time:
long time = System.currentTimeMillis();
using the current time and the some time in the past you can find the
difference. Time in the past can be obtained via the codes from above.
Joda Time User Guide

public void onCreate(Bundle savedInstanceState) {
long currentTime = System.currentTimeMillis();
sendToMethod(currentTime);
}
public void sendToMethod(long currentTime) {
long diff = currentTime - pastTime;
if (diff > 10000){
// Do some thing here...
}
}

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)
}

How to create a countdown till a specific day Android

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;
}

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.

Determining if a time is between two other times

I am trying to take hours that I've parsed using SimpleDateFormat and determining whether or not the current time is between the two sets of hours. Basically, given a place's hours, I'm trying to determine if it is currently open our closed.
I am getting the current time by doing the following:
SimpleDateFormat sdf2 = new SimpleDateFormat("kk:mm");
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
String currentHour = Integer.toString(hour);
String currentMinute = Integer.toString(minute);
String timeNow = currentHour + ":" + currentMinute;
Date timeRightNow = sdf2.parse(timeNow);
Then, I determine whether timeRightNow is between the opening and closing times, I am doing the following:
if (timeOpen.before(timeRightNow) && timeClose.after(timeRightNow)) {
openStatus = "open!";
} else {
openStatus = "closed.";
}
Both timeOpen and timeClose are found by parsing a String using sdf2 in the exact same way as timeRightNow is found.
Every time that this runs, it sets openStatus to "closed." even when the current time is between the open and close times. Can anyone point me in the right direction to figure out why this is happening?
I changed Calendar.HOUR to Calendar.HOUR_OF_DAY. This resolved the issue.

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/

Categories

Resources