how to subtract system time from user defined time - java

can anybody suggest me to find interval between system time and user defined time as my hour =20 and minute =12.I just want to find interval between this two times and need to set this time for countdown timer

To get difference between any two date/calendar objects it's better to get time in milliseconds(long).
Calendar current = Calendar.getInstance();
Calendar usertime = Calendar.getInstance();
usertime.set(Calendar.HOUR_OF_DAY, 20);
usertime.set(Calendar.MINUTE, 12);
long diffInMilisecond = Math.abs(usertime.getTimeInMillis()-current.getTimeInMillis());

If you can use third party api, then Joda time will hold very good for the above scenario. See here

Why go through all the trouble of having the user enter in the time he wants instead of how long from the current time? It makes more sense when mapping to the idea of a countdown timer.
If you want to set a timer for a user specified time this is how I would do it.
//Get user input into variable hours, and minutes
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
//do stuff when countdown has happened
}, (((hours * 60) + minutes) * 60) * 1000)); //time in milliseconds to exec run
}
EDIT
If you simply want to calculate the difference in time when the user inputs hour and minute try the following:
//Get user input into variable hours, and minutes
Calendar cal = new GregorianCalendar();
//Assuming user inputs hour in 24 hour format and inputted time is in future
totalMinsDiff = (hours - cal.get(Calendar.HOUR_OF_DAY)) * 60 +
minutes - cal.get(Calendar.MINUTE);
countdownHours = totalMinsDiff / 60;
countdownMins = totalMinsDiff % 60;

Related

How to transfer Date.getTime() to hours and calculating difference

I have a program that is intaking an "AM" "PM" time and calculating out the hours in the day equivalent (in 24 hour format). For some reason it parses and calculates the time I input to the incorrect 24 hour equivalent (ie 5:00 pm comes to equal 22)
System.out.print("Enter the end time (HH:MM am): ");
endTime = input.nextLine();
Date ETime = time_to_date.parse(endTime);
Class method
public int get_Family_A_Calulation(Date STime, Date ETime) {
Date startTimeCalc = STime, endTimeCalc = ETime;
int pay = 0, hoursWorked, StartHour, EndHour;
StartHour = ((((int) startTimeCalc.getTime()) / 1000) / 60) / 60;
EndHour = ((((int) endTimeCalc.getTime()) / 1000) / 60) / 60;
pay = hoursWorked * 15;
return pay;
}
I am not sure where my error is can anyone give me advice on how to correct this error?
Use the latest classes available fron java8
LocalDateTime now = LocalDateTime.now();
System.out.println(now.getHour());
The actual data behind Date is milliseconds since the epoch. Any hour or time representation is based on the calendar date portion and takes into account timezone and daylight savings.
Regardless of what you do, there will be calculation issues across days, etc.
As suggested by Scary Wombat, use the new classes in java.time package. For your specific case, you need a LocalTime as the code is trying to represent a time element (hours, minutes, seconds, etc) without consideration for Date, TimeZone, etc.
https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html

Find the difference in time between two time values always gives the "Second" value as 0

I'm trying to find the difference between current time value and a future time in HH:MM:SS format.
For example:
When date1 is "2017-05-11T20:30" and date2 is "2017-05-11T21:40", the output should be 01:10:00.
Here's the code I'm trying, wherein I'm trying to find the difference between current time and a future time value:
public void updateTimeRemaining() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
String currentTime = simpleDateFormat.format(new Date());
long difference = simpleDateFormat.parse(endTime).getTime() - simpleDateFormat.parse(currentTime).getTime();
if (difference>0) {
String hms = String.format("%02d:%02d:%02d", millisLeft/(3600*1000),
millisLeft/(60*1000) % 60,
millisLeft/1000 % 60);
textView.setText(hms); //setting the remaining time in a textView
}
}
I'm invoking the method updateTimeRemaining() every second so that the textview gets updated every second like a timer. The problem I'm facing is seconds value always returns 0. Instead I would like the seconds value to be updated every second like below:
01:50:45
01:50:44
01:50:43
01:50:42...
You could use
difference = simpleDateFormat.parse(endTime).getTime() - new Date().getTime();
in place of these lines of your code:
String currentTime = simpleDateFormat.format(new Date());
long difference = simpleDateFormat.parse(endTime).getTime() - simpleDateFormat.parse(currentTime).getTime();
This should work fine.
You can use CountDownTimer. Here is an example :
new CountDownTimer(30000, 1000) { // 30 seconds countdown
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
The Constructor is : CountDownTimer(long millisInFuture, long countDownInterval)
You are performing a subtraction of two values and taking action if the result is greater than 0. Since it is not, it means endTime is necessarily not in the future but is before currentTime.
Fix your endTime problem.
I got three suggestions.
To me the natural suggestion is you use the classes in java.time. They are much nicer to work with than the outdated Date and SimpleDateFormat that are built-in with your Android Java.
long endMillis = LocalDateTime.parse(endTime,
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm"))
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli();
long difference = endMillis - System.currentTimeMillis();
The rest will be the same as in your code. To use LocalDateTime and DateTimeFormatter on Android you will need to get ThreeTenABP, it contains the classes.
I wish I could tell you to use Duration, another one of the newer classes. However, Duration doesn’t seem to lend itself well to formatting. This will change with Java 9 (not tested):
LocalDateTime endDateTime = LocalDateTime.parse(endTime,
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm"));
Duration diff = Duration.between(LocalDateTime.now(ZoneId.systemDefault()),
endDateTime);
if (! diff.isNegative()) {
String hms = String.format("%02d:%02d:%02d",
diff.toHoursPart(),
diff.toMinutesPart(),
diff.toSecondsPart());
textView.setText(hms); //setting the remaining time in a textView
}
Isn’t that beautiful and clear?
If you don’t want the dependency on ThreeTenABP, there is of course a fix to your code. It’s even a simplification. In your code you are formatting the new Date() that you are getting the current time from, without seconds, so they get lost, and then parsing it again, and finally getting its milliseconds since the epoch. Skip all of that and just get the current time from System.currentTimeMillis() just as in the first snippet above:
long difference = simpleDateFormat.parse(endTime).getTime()
- System.currentTimeMillis();
This will give you your seconds.

Remaining time from current time to 18:30 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i want learn remaining time from current time to 18.30
My code is not working:
long currentTime = System.currentTimeMillis();
long endTime = 18:30;
long remaining = endTime - currentTime;
long hours = remaining / 3600000;
long mins = remaining / 60000 % 60;
long seconds = remaining / 1000 % 60;
String remainingText = String.format("%02d:%02d:%02d", hours,mins,seconds);
long endBidTime = ();
As you know, this causes a compiler error. From the comments, you seem to want to set this to 18:30 on the current day. One solution is to use the Date object. You will first need to create a Date object and set its time to 18:30. See the javadocs for the Date class for details about how to do this. You will also need to use Date.currentTimeMillis() to get the correct value for endBidTime.
You have another problem in your code:
String remainingText = "%02d:%02d:%02d".format(hours,mins,seconds);
This is incorrect and probably gives other compiler errors. Note that the format() method is static. Even though Java allows us to call static method with an instance variable, it is strongly discouraged. Instead, you should use the class name. Also, the format string is the first parameter that format() expects. This means you should do the following:
String remainingText = String.format("%02d:%02d:%02d", hours,mins,seconds);
currentTimeMillis() returns the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC. See here.
If you want to find the remaining time left till today 18:30. You have to first find the time in milliseconds at today 18:30 (then find the difference), here is my code:
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import static java.util.concurrent.TimeUnit.*;
public class timetill1830 {
public static void main(String[] args) {
int hr = 18, min = 30, sec = 0;
Calendar calendar = Calendar.getInstance();
//Now set the time for today 18:30
Calendar cal = new GregorianCalendar(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH), hr, min, sec);
System.out.println(cal.getTimeInMillis());
System.out.println(System.currentTimeMillis());
// Now Print time left till 18:30
System.out.println("Time in millsec. till 18:30 = "
+ (cal.getTimeInMillis() - System.currentTimeMillis()));
formattedTimeLeft(cal.getTimeInMillis() - System.currentTimeMillis());
}
private static void formattedTimeLeft(long millis) {
int hrs = (int) (MILLISECONDS.toHours(millis) % 24);
int min = (int) (MILLISECONDS.toMinutes(millis) % 60);
int sec = (int) (MILLISECONDS.toSeconds(millis) % 60);
//int mls = (int) (millis % 1000);
System.out.println("Time left "+hrs+" hours "+min+" minutes "+sec+" seconds");
}
}

Checking if its been 24 hours

I need to write a method that can only execute once every 24 hours. It grabs a string, called "lastCollection", then should parse it to some sort of time object. It should then get the current time, and check if it has a 24 hour difference from "lastcollection". If so, it should execute some code, and set lastCollection to a new readable time string. Whats the best way to go about doing this?
Is this called by something or is this something that needs to be ran once every 24 hours?
If Possible you can just sleep it. I'll need a code example to show you how to fit it in but.
In case of once a day On a Schedule
Get Time at start of method.
Perform Method
Get New Time
Get Difference in Start Time and Current Time
Sleep the remainder of the time until same start time of the next day.
OR
Need to check before Performing
Get Time at start of method save to variable
Every time this method is called check a difference in a value say Minutes(see below)
If it is greater than 24 then repeat the method
Date Diffs can be done like this:
Date lasttimeran = null;
Date now = null;
long diff = now.getTime() - lasttimeran.getTime();
long diffMinutes = diff / (60 * 1000);
//If block to check if it has been long enough >= ensures a diff of exactly 24 hours will still trigger the method to be ran
if (diffMinutes >= 1440) {
//Do Something
}
else{
//Do Nothing
}
Calendar expCal = Calendar.getInstance();
while (true) {
expCal.add(Calendar.HOUR, 24);
Date expirationDate = expCal.getTime();
Date currentDate = new Date();
if (currentDate.compareTo(expirationDate) == 0)
//Do your Work here
expCal = Calendar.getInstance();
}

Whats is the right way to get elapsed time and reset it

In my android program I am using two Calendar instances to get the elapsed time in my program, first I set a level starting time as follows:
level_Start_TimeCal = Calendar.getInstance();
and in my thread I am calculating elapsed time as follows:
level_current_TimeCal = Calendar.getInstance();
gameTime = level_current_TimeCal.getTimeInMillis()- level_Start_TimeCal.getTimeInMillis();
dsecs = (gameTime / 1000)%60;
dminutes = (gameTime / (60 * 1000))%60;
dhours = (gameTime / (60 * 60 * 1000))%60;
Recently I came to read the following:
Calendar's getInstance method returns a Calendar object whose calendar
fields have been initialized with the current date and time
I want to know if I am in right path?
Am I creating an object each time the thread running?
If yes is there any alternative to avoid creating unwanted objects and calculating elapsed time?
Final question: at some point I want to reset the time in my restart method I reset it by just calling getInstance in my reset method as follows:
public void restart() {
level_Start_TimeCal = Calendar.getInstance();
}
Is this the correct way to reset the Calendar?
The best way to calculate elapsed time is to use System.nanotime().
long start = System.nanoTime();
//do something
long end = System.nanoTime();
//to get the elapsed time, you can use the TimeUnit utility methods:
long elapsedInNanos = end - start;
long elapsedInSeconds = TimeUnit.SECONDS.convert(elapsedInNanos, TimeUnit.NANOSECONDS);
Note that it is not a useful method to access absolute time.

Categories

Resources