Hi, I would like to run method interval of every 15 minutes .
Example: If my application initial server start time example 0:12 it
won't be call timer scheduler run method.
so my timer scheduler run method particular interval of every
hourly 15 minutes like :
0:15,0:30,0:45,1:00,1:15,1:30,1:45,2:00,2:15,2:30,2:45,.....etc.
Below sample snippet code always run method executed when initial
application start please let me know where I have made mistaken?
As per my requirement I need to implement in Timer-Task Scheduler.
private class TimerExample{
private static Timer timer = new Timer();
private static Calendar getFirstTime() {
Calendar cal = Calendar.getInstance();
int currentMinute = cal.get(Calendar.MINUTE);
if (currentMinute < 45) {
cal.set(Calendar.MINUTE, 45);
}
if (currentMinute < 30) {
cal.set(Calendar.MINUTE, 30);
}
if (currentMinute < 15) {
cal.set(Calendar.MINUTE, 15);
}
if (currentMinute >= 45) {
cal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY) + 1);
cal.set(Calendar.MINUTE, 0);
}
cal.set(Calendar.SECOND, 0);
return cal;
}
public static void main(String... args) {
Calendar firstTaskTime = getFirstTime();
System.out.println("Task will start at: " + firstTaskTime.getTime());
timer.schedule(new MyTask(), firstTaskTime.getTime(), 1000 * 60 * 15);
}
}
Related
I have already written a 60 seconds countdown timer but I would like to transform this to have a minutes and seconds timer like mm:ss.
Can I rearrange this existing code to get that ?
Timer timer = new Timer();
TimerTask task = new TimerTask() {
int i = 60;
public void run(){
if (i >= 0) {
lab3.setText("Timer " + i--);
}
}
};
timer.scheduleAtFixedRate(task, 0, 1000);
You need to display remaining number of second i in format mimutes:seconds format. If you assume that there are always 60 seconds in a minute:
String time = String.format("%02d:%02d", i / 60, i % 60);
System.out.println(time);
I am making an app which can show time left to some date, and an elapsed time after some date. But I endure some difficulties with dates less than 1970 and bigger than 3300. I have found an explanation why it happens.
The problem is this sentence from getTimeInMillis:
the current time as UTC milliseconds from the epoch.
And, as far as i remember, the epoch started on January 1st 1970 you get a negative number for anything before that.
My question is how to solve this problem. (And yes i have heard about JodaTime, I am not allowed to use this library in this app.)
What default(standard) tools should i use?
Here it is a piece of code that does not work properly.
private void getDateTime()
{
Date date = new Date();
timeRemaining = Calendar.getInstance();
date.setTime(timeRemaining.getTimeInMillis());
millis = Math.abs(timeRemaining.getTimeInMillis() - targetDate.getTimeInMillis());
int scnds = (int) (millis / 1000) % 60 ;
int mnts = (int) ((millis / (1000 * 60)) % 60);
int hrs = (int) ((millis / (1000 * 60 * 60)) % 24);
int dys = (int) (millis / (1000 * 60 * 60 * 24));
resultDate.setText(getString(R.string.formating, dys, hrs, mnts, scnds));
}
You can achieve this by leveraging the Duration and LocalDateTime class(es) introduced in Java 8 --
import java.time.Duration;
import java.time.LocalDateTime;
class Main {
public static void main(String[] args) {
LocalDateTime fromDateTime = LocalDateTime.of(1914, 9, 10, 0, 0, 0);
LocalDateTime toDateTime = LocalDateTime.of(2014, 12, 16, 0, 0, 0);
System.out.println(Duration.between(fromDateTime, toDateTime).toMillis());
}
}
Hi i am trying to calculate difference of two dates in days. The dates are 14 of this month and today. It should be 2. But o/p is 0 always.
Code:
long today = (new java.util.Date().getTime());
long difference =(long) (today - 1394809789186.0);
long daysdifference = difference/(24*3600*1000);
System.out.println(daysdifference);
o/p:
0.
whats wrong?
Now i did another trick and it gives perfect answer dont know whats wrong with above code...
SimpleDateFormat df = new SimpleDateFormat("dd.mm.yyyy");
long firstdateseconds = df.parse("14.03.2014").getTime();
long today = df.parse("16.03.2014").getTime();
long difference = (today-firstdateseconds);
long days = (long)(difference/(24*3600*1000));
System.out.println(days);
o/p : 2 // now correct bingo!
Guys whats happening?
I used the following simple code to accomplish what you want:
import java.util.Date;
public class datediff {
public static void main(String[] args) {
Date d1 = new Date();
Date d2 = new Date(2014 - 1900, 2, 14);
long d1_millis = d1.getTime();
long d2_millis = d2.getTime();
long diffMillis = d1_millis - d2_millis;
long diffDays = diffMillis / (24 * 3600 * 1000);
System.out.println("Difference in days: " + diffDays);
}
}
OUTPUT:
Difference in days: 2
Also note that the magic number that you are using while calculating the difference is incorrect.
The actual value to subtract is : 1394735400000
That is the most dangerous disadvantage of using magic numbers.
Hope that clarifies things for you.
Perhaps a combined TimeZone and "Time (hours/minutes/seconds)" issue?
Case I
Different timezones and different day times:
public static void main(final String[] args) {
final Calendar march14 = Calendar.getInstance(TimeZone.getTimeZone("US/Hawaii"));
march14.set(2014, Calendar.MARCH, 14, 23, 59, 0);
final Calendar march16 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Tokyo"));
march16.set(2014, Calendar.MARCH, 16, 0, 0, 0);
final long diffInMs = march16.getTimeInMillis() - march14.getTimeInMillis();
System.out.println("diff = " + diffInMs / (24 * 3600 * 1000)+" day(s)");
}
This prints:
diff = 0 day(s)
Case II
However, adjusting the time zone:
public static void main(final String[] args) {
final Calendar march14 = Calendar.getInstance(TimeZone.getTimeZone("US/Hawaii"));
march14.set(2014, Calendar.MARCH, 14, 23, 59, 0);
final Calendar march16 = Calendar.getInstance(TimeZone.getTimeZone("US/Hawaii")); // <- CHANGE!
march16.set(2014, Calendar.MARCH, 16, 0, 0, 0);
final long diffInMs = march16.getTimeInMillis() - march14.getTimeInMillis();
System.out.println("diff = " + diffInMs / (24 * 3600 * 1000)+" day(s)");
}
This prints:
diff = 1 day(s)
Case III
And adjusting the time (hours/minutes/seconds):
public static void main(final String[] args) {
final Calendar march14 = Calendar.getInstance(TimeZone.getTimeZone("US/Hawaii"));
march14.set(2014, Calendar.MARCH, 14, 0, 0, 0); // <- CHANGE!
final Calendar march16 = Calendar.getInstance(TimeZone.getTimeZone("US/Hawaii"));
march16.set(2014, Calendar.MARCH, 16, 0, 0, 0);
final long diffInMs = march16.getTimeInMillis() - march14.getTimeInMillis();
System.out.println("diff = " + diffInMs / (24 * 3600 * 1000)+" day(s)");
}
This prints:
diff = 2 day(s)
Conclusions
My two advices:
Don't use magic numbers, set all parts of your date/calendar objects that are relevant
Always set the TimeZone when working with date/time
Additional note to SimpleDateFormat
By the way: In SimpleDateFormat m is for minutes, M for month in year, see http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. It was pure random that the result of your calculations was 2.
Use double you are crossing a truncation issue
I have a Timer working with JavaFX but all it will count is seconds. How would I get it to do Minutes and Seconds.
timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.getKeyFrames().add(
new KeyFrame(Duration.seconds(1),
//new {
new EventHandler<ActionEvent>() {
// KeyFrame event handler
public void handle(ActionEvent event) {
remaining--;
// update timerLabel
timeStamp.setText(
remaining.toString());
if (remaining <= 0) {
timeline.stop();
}
}
}));
timeline.playFromStart();
Duration newValue=timeline.getCurrentTime();
int hTime = (int) newValue.toHours();
int minTime = (int) newValue.toMinutes();
int secTime= (int) newValue.toSeconds();
if(secTime/60>=1){ // this are to display later something like a clock 19:02:20
secTime%=60; //if you want just the time in minutes use only the toMinutes()
}
if(minTime/60>=1){
minTime%=60;
}
hTime = time in hours
minTime = time in minutes
secTime = time in seconds
usually the timeline works with millis so you have to be careful ;)
You Use getTime Method
http://docs.oracle.com/javafx/2/api/javafx/animation/KeyFrame.html
I think this will help you .
You may use java.util.concurrent.TimeUnit class which provides nice conversion facilities
int min = 3;
int sec = 14;
double totalSec = TimeUnit.MINUTES.toSeconds(min) + sec;
I am trying to display a countup timer with format 1.00 resolution. basically seconds and with hundredths of second or 10ms resolution.
I have tried the chronometer function but still no luck, it seems it can only track 1 second resolution.
here is some of my code:
public void stopwatch() {
stopWatch.setOnChronometerTickListener(new OnChronometerTickListener(){
#Override
public void onChronometerTick(Chronometer arg0) {
countUpmilli = (Long) ((SystemClock.elapsedRealtime() -arg0.getBase())/ 100);
countUpSec = (Long) ((SystemClock.elapsedRealtime() -arg0.getBase()) / 1000);
//asText = (countUp / 60) + ":" + (countUp % 60);
asText = (countUpSec / 1) + "." + (countUpmilli%100);
timertext.setText(asText);
}
});
stopWatch.start();
}
I think you have to use System.nanoTime();