Adding days to Date periodically in Java - java

I want to add days to the current date periodically.
For example, I every 10 seconds that passes, I want to add 1 day to the date today.
08/09/2019 after 10 seconds turns to 08/10/2019...I've already got a working timer, I just dont know how to implement the adding of days part
TimerTask task = new TimerTask() {
#Override
public void run() {
day = day + 1;
model.setDay(day);
Calendar c = Calendar.getInstance();
if(model.getDay() ==1)
c.setTime(date);
Calendar d = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, 1);
d.add(Calendar.DAY_OF_MONTH, 0);
String currentDate = dates2.format(c.getTime());
String currentDate2 = dates2.format(d.getTime());
model.setUpdateDate(currentDate);
model.setUpdateDate2(currentDate2);
}
};
Timer timer = new Timer();
long delay = 10000;
long intervalPeriod = 10000;

You should use java.time types instead of Date and Calendar, which are considered legacy types since Java 8.
Here's an example that may suit you:
public class CountingDays {
private LocalDate date = LocalDate.now();
public static void main(String[] args) {
CountingDays countingDays = new CountingDays();
TimerTask task = new TimerTask() {
#Override
public void run() {
countingDays.date = countingDays.date.plusDays(1);
System.out.println(countingDays.date);
}
};
Timer timer = new Timer();
long delay = 0;
long intervalPeriod = 10_000;
timer.schedule(task, delay, intervalPeriod);
}
}

Related

Running timer task at 0200 hrs everyday

I have a timer ejb that controls when the application runs that needs to be switched. I need to make it to run at 0200 hrs everyday
public void fireInTwentyFourHours() throws EJBException
TimerService theTimerService = mySessionCtx.getTimerService();
String aLabel = "24 Hours Interval";
//theTimerService.createTimer(new Date(),86400000, aLabel);
String stage = Stage.getStage();
List timerObjects = (List)theTimerService.getTimers();
if(null != timerObjects && timerObjects.size() > 0) {
for(int timerCount=0,size=timerObjects.size();timerCount<size;timerCount++) {
Timer timer = (Timer)timerObjects.get(timerCount);
timer.cancel();
}
}
if(stage.equalsIgnoreCase("P")){
theTimerService.createTimer(getRunTime(),86400000, aLabel);
} else {
theTimerService.createTimer(new Date(),86400000, aLabel);
}
}
private Date getRunTime() {
Calendar gc = new GregorianCalendar();
int year = gc.get(Calendar.YEAR);
int month = gc.get(Calendar.MONTH);
int date = gc.get(Calendar.DAY_OF_MONTH);
Calendar newDate = new GregorianCalendar(year,month,date,17,30,0);
return newDate.getTime();
}
I need to create a new method and make fireInTwentyFourHours to execute at 0200 hrs.
Is this the correct way to make it fire at 0200
public Date getTime(){
Calendar c = Calendar.getInstance();
Date d = c.getTime();
return d;
}
public void fireInTwentyFourHours() throws EJBException
TimerService theTimerService = mySessionCtx.getTimerService();
String aLabel = "24 Hours Interval";
//theTimerService.createTimer(new Date(),86400000, aLabel);
String stage = Stage.getStage();
List timerObjects = (List)theTimerService.getTimers();
if(null != timerObjects && timerObjects.size() > 0) {
for(int timerCount=0,size=timerObjects.size();timerCount<size;timerCount++) {
Timer timer = (Timer)timerObjects.get(timerCount);
timer.cancel();
}
}
if(stage.equalsIgnoreCase("P")){
theTimerService.createIntervalTimer(getTime(),86400000, aLabel);
} else {
theTimerService.createIntervalTimer(new Date(),86400000, aLabel);
}
}
the third parameter is timerConfig how to set that. will it make the code to run at 0200?

How to correct calculate the running time

I want to calculate the total running time of my program from start to end and refresh running time in JFrame, but when I run my program I get excess 70 years, 1 day and 2 hours. Why ? What wrong ?
private void setMachineTime(){
Timer timer = new Timer();
long startTime = new Date().getTime();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
long endTime = new Date().getTime();
long diffTime = endTime - startTime ;
String time = new SimpleDateFormat("yy:mm:dd:HH:mm:ss").format(diffTime);
System.out.println(time);
}
}, 0, 1000);
}
actual result
UPD:
I rewrote code with my own format time method. Now I got what I want. Thanks to all of you.
private void setMachineTime(){
Timer timer = new Timer();
long startTime = new Date().getTime();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
long endTime = new Date().getTime();
long diffTime = endTime - startTime;
String diffSeconds = formatTime(diffTime / 1000 % 60);
String diffMinutes = formatTime(diffTime / (60 * 1000) % 60);
String diffHours = formatTime(diffTime / (60 * 60 * 1000) % 24);
System.out.println(diffHours + ":" + diffMinutes + ":" + diffSeconds);
}
}, 0, 1000);
}
private String formatTime(long diff){
long t;
t = diff;
if(t < 10){
return String.valueOf("0"+t);
} else {
return String.valueOf(t);
}
}
You are formatting the time difference as yy:mm:dd:HH:mm:ss. Just printing out diffTime would give you the milliseconds, divide by 1000 if you need seconds.
EDIT: I think i see what you are trying to do, but you are dealing with a time interval, which cannot be formatted as a date. You'll need to roll your own formatting for displaying the time as seconds, minutes, hours etc. or use an external library.
getTime return number of milliseconds from 1.1.1970...and same is for SimpleDateFormat converting number to date (and then formating it). It means when your diffTime = 0, SimpleDateFormat will try to format Date 1.1.1970 0:00:00 and with your formating string it will be 70:01:01:00:00:00. Try to use http://joda-time.sourceforge.net/api-release/org/joda/time/Interval.html instead.
And by the way, your formating string is wrong anyway...you use mm where I supouse you wanted month...but mm are minutes.

JSpinner time constraint

I am trying to create a spinner that has hours and minutes. The minutes part needs to increment by 10 mins only and the time must range from the current time to an end time. I also need the minimum value (previously current time) to update to current time.
I tried playing around with it, but I just couldn't get it to work.
JSpinner spinner1 = new javax.swing.JSpinner();
SpinnerDateModel spinnermodel = new SpinnerDateModel();
spinnermodel.setCalendarField(Calendar.MINUTE);
spinner1.setModel(spinnermodel);
spinner1.setEditor(new JSpinner.DateEditor(spinner1, "hh:mm"));
SpinnerModel model = new SpinnerDateModel(currentDate, currentDate, latestDate, Calendar.MINUTE * 10 ?);
The SpinnerDateModel just uses 1 to increment the field you want to change.
I extended the SpinnerDateModel to add an addition property to the model to control the increment value instead of hard coding to 1:
import java.util.*;
import javax.swing.*;
public class MySpinnerDateModel extends SpinnerDateModel
{
private int increment = 1;
public MySpinnerDateModel(Date value, Comparable start, Comparable end, int calendarField)
{
super(value, start, end, calendarField);
}
public MySpinnerDateModel()
{
this(new Date(), null, null, Calendar.DAY_OF_MONTH);
}
public void setIncrement(int increment)
{
this.increment = increment;
}
public int getIncrement()
{
return increment;
}
#Override
public Object getNextValue()
{
Calendar cal = Calendar.getInstance();
Date value = (Date)getValue();
cal.setTime(value);
cal.add(getCalendarField(), increment);
Date next = cal.getTime();
Comparable end = getEnd();
return ((end == null) || (end.compareTo(next) >= 0)) ? next : null;
}
#Override
public Object getPreviousValue()
{
Calendar cal = Calendar.getInstance();
Date value = (Date)getValue();
cal.setTime(value);
cal.add(getCalendarField(), -increment);
Date prev = cal.getTime();
Comparable start = getStart();
return ((start == null) || (start.compareTo(prev) <= 0)) ? prev : null;
}
}
You should be able to use the model the way you did before but with one additional statement:
MySpinnerDateModel model = new MySpinnerDateModel(currentDate, currentDate, latestDate, Calendar.MINUTE);
model.setIncrement( 10 );
You can extend the SpinnerDateModel to specify the behavior. Below is an example in which the getNextValue and getPreviousValue are overridden to return values +/- 10 minutes:
Date now = new Date();
Date start = now;
final long tenMinutesInMillis = 1000 * 60 * 10;
Date end = new Date(now.getTime() + tenMinutesInMillis * 60);
SpinnerModel model = new SpinnerDateModel(now, start, end, Calendar.MINUTE){
#Override
public Object getNextValue(){
Date newDate = new Date(getDate().getTime() + tenMinutesInMillis);
Date endDate = (Date)getEnd();
return newDate.getTime() > endDate.getTime() ? endDate : newDate;
}
#Override
public Object getPreviousValue(){
Date newDate = new Date(getDate().getTime() - tenMinutesInMillis);
Date startDate = (Date)getStart();
return newDate.getTime() < startDate.getTime() ? startDate : newDate;
}
};

Android countdown not working

Trying to make a small countdown timer in my app but it's not working.
Idea is to count down to a specific time. First by days and when it gets closer, by hours.
The following method is inside my Fragmentclass.java (so it's a fragment)
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
Calendar cal = Calendar.getInstance();
cal.set(2012, 8, 29, 10, 0);
long endTime = cal.getTimeInMillis();
long currentTime = System.currentTimeMillis();
long remaining = currentTime - endTime;
long seconds = remaining / 1000 % 60;
new CountDownTimer(seconds, 1000) {
TextView tv = (TextView)getActivity().findViewById(R.id.introTimeLeft);
public void onTick(long millisUntilFinished) {
Calendar cal = Calendar.getInstance();
cal.set(2012, 8, 29, 10, 0);
long endTime = cal.getTimeInMillis();
long currentTime = System.currentTimeMillis();
long remaining = currentTime - endTime;
long hours = remaining / 3600000;
long mins = remaining / 60000 % 60;
long seconds = remaining / 1000 % 60;
long days = hours / 24;
String remainingText = String.valueOf(days) + " days";
Log.i("countdown",String.valueOf(days));
tv.setText("Days left: " + days);
}
public void onFinish() {
Log.i("countdown","CD Finished");
tv.setText("CD Finished!");
}
}.start();
}
Note that the textbox value is just for testing right now, but i can't seem to get it to display the countdown.
Also is this the best approach?
Here are the values of the variables if I run your code:
endTime = 1348902045437
currentTime = 1340645325437
remaining = -8256720000
seconds = 0
as you see seconds == 0, and this is the reason.
Also note that the first argument in the CountDownTimer(long millisInFuture, long countDownInterval) constructor is
The number of millis in the future from the call to start() until the
countdown is done and onFinish() is called.
So a fixed code would be:
Calendar cal = Calendar.getInstance();
cal.set(2012, 8, 29, 10, 0);
long endTime = cal.getTimeInMillis();
long currentTime = System.currentTimeMillis();
long remaining = endTime - currentTime;
new CountDownTimer(remaining, 1000) {
...
UPDATE:
It is odd it does not update the text view. The only idea I can propose is to run update calls on the main UI thread. It should be something like this:
public void onTick(long millisUntilFinished) {
final String days = .. // some code to generate days
getActivity().runOnUiThread(new Runnable() {
public void run() {
tv.setText("Days left: " + days);
}
});
}
public void onFinish() {
Log.i("countdown","CD Finished");
getActivity().runOnUiThread(new Runnable() {
public void run() {
tv.setText("CD Finished!");
}
});
}
If this doesn't help - then I'm out of ideas.

TimerTask not executing?

Here is my timer class, This class is designed to constantly update a timer in a view. However, when I run the app the first toast message is displayed to the screen but the second one is never reached (the timerTask's "run" method is never executed). I know that this is probably something simple that I am doing wrong. If anyone could steer me in the right direcion that would be great.
public class MyTimer {
static Timer _timerTask = new Timer();
static int totalSeconds = 1, hour = 0, min = 0, sec = 0;
static String mTimeFormat = "%02d:%02d:%02d";
static String timeTakenString;
public static void start (){
Toast.makeText(GPSMain.context, "Message one", Toast.LENGTH_LONG).show();
TimerTask timer = new TimerTask() {
#Override
public void run() {
Toast.makeText(GPSMain.context, "Message two", Toast.LENGTH_LONG).show();
totalSeconds += 1;
sec += 1;
if(sec >= 60) {
sec = 0;
min += 1;
if (min >= 60) {
min = 0;
hour += 1;
}
}
timeTakenString = String.format(mTimeFormat, hour, min, sec);
postExecute.sendEmptyMessage(0); //update UI
}
private Handler postExecute = new Handler(){
public void dispatchMessage(Message msg) {
super.dispatchMessage(msg);
GPSMain.timer.setText("Time Taken: "+timeTakenString);
}
};
};
_timerTask.scheduleAtFixedRate(timer,1000,1000);
}
}
code in another file calling this class:
MyTimer myTimer = new MyTimer();
....
myTimer.start();
PROJECT SPEC CHANGED!
My project leader changed the spec of the project so that it no longer needs to update the timer to the UI but rather display it as an end result. Accepting the first answer anyway as it solves the original problem. Will post the new code below.
New code calls:
System.currentTimeMillis();
at the beggining and end of the runcycle, which returns a long. The first value is then subtracted from the second value to calculate the amount of time taken to execute the runcycle. That value is then manipulated and put into a timer format that is displayed at the end as a string.
public static String getTimeTaken(long end, long start){
#SuppressWarnings("unused")
String formattedTime = "", hourHour = "", hourMin = ":", minSec = ":";
long timeTaken = (end-start)/1000, hour = 0, min = 0, sec = 0;
if (timeTaken>9 ){
hourHour = "0";
hourMin = ":0";
if (timeTaken>=60){
if (timeTaken>= 3200){
hour = timeTaken/3200;
timeTaken = timeTaken%3200;
if (hour>9){
hourHour = "";
}
}
min = timeTaken/60;
timeTaken = timeTaken%60;
if (min >9){
hourMin = ":";
}
}
sec = timeTaken;
if(sec%60<10){
minSec = ":0";
}
return formattedTime = (hourHour+hour+hourMin+min+minSec+sec);
}
sec = timeTaken;
minSec = ":0";
hourMin = ":0";
hourHour = "0";
return formattedTime = (hourHour+hour+hourMin+min+minSec+sec);
}
Using thread you cant update your UI for that you have to use runOnUiThread
youractivity.this.runOnUiThread(new Runnable(){public void run(){Toast.makeText(mContext, "Message", Toast.LENGTH_LONG).show();}});
(Very late...just answering in case someone reach this question... scheduling a task doesn't garantee it will run on the proper time... it may take longer, sometimes much longer...)

Categories