Countdown Timer that is date and time specific - java

txtTimerDay = (TextView) findViewById(R.id.txtTimerDay);
txtTimerHour = (TextView) findViewById(R.id.txtTimerHour);
txtTimerMinute = (TextView) findViewById(R.id.txtTimerMinute);
txtTimerSecond = (TextView) findViewById(R.id.txtTimerSecond);
tvEvent = (TextView) findViewById(R.id.tvhappyevent);
countDownStart();
}
public void countDownStart() {
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 1000);
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd");
// Please here set your event date//YYYY-MM-DD
Date futureDate = dateFormat.parse("2017-03-18");
Date currentDate = new Date();
if (!currentDate.after(futureDate)) {
long diff = futureDate.getTime()
- currentDate.getTime();
long days = diff / (24 * 60 * 60 * 1000);
diff -= days * (24 * 60 * 60 * 1000);
long hours = diff / (60 * 60 * 1000);
diff -= hours * (60 * 60 * 1000);
long minutes = diff / (60 * 1000);
diff -= minutes * (60 * 1000);
long seconds = diff / 1000;
Okay... Here is my question... Currently in this code... The Output which includes the layout and some more lines...
Will generate a proper timer heading towards march 18th... However... I need the timer to countdown towards march 18th at 20.30 at night.. Any Help will be appreciated and please tolerate me.. i am new in this website

import java.util.Date;
import java.util.Calendar;
public class cal {
public static int SECONDS_IN_A_DAY = 24 * 60 * 60;
public static void main(String[] args) {
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(new Date(0)); /* reset */
thatDay.set(Calender.HOUR_OF_DAY,2);/*here Add ur Time */
thatDay.set(Calendar.DAY_OF_MONTH,1);
thatDay.set(Calendar.MONTH,0); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 2014);
Calendar today = Calendar.getInstance();
long diff = thatDay.getTimeInMillis() - today.getTimeInMillis();
long diffSec = diff / 1000;
long days = diffSec / SECONDS_IN_A_DAY;
long secondsDay = diffSec % SECONDS_IN_A_DAY;
long seconds = secondsDay % 60;
long minutes = (secondsDay / 60) % 60;
long hours = (secondsDay / 3600); // % 24 not needed
System.out.printf("%d days, %d hours, %d minutes and %d seconds\n", days, hours, minutes, seconds);
}
}
Try To use Calender It will help to set your Time and Date Try it....do not forget to accept if goal is accomplished

Related

Update textview every x seconds to show notification in background

I have this code
public void LoadCurrentTime(long time_last) {
long millis_now = System.currentTimeMillis();
long time_till = millis_now - time_last;
String showTime;
int showHours, showMin, showSec;
if (time_till > 604800000) {
showTime = getString(R.string.long_ago);
} else {
//long longHours = (time_till / 1000 / 60 / 60);
//long longMin = (time_till / 1000 / 60 % 60);
//long longSec = (time_till / 1000 % 60);
//showHours = (int) longHours;
//showMin = (int) longMin;
//showSec = (int) longSec;
//showTime = String.format("%02d", showHours) + ":" + String.format("%02d", showMin) + ":" + String.format("%02d", showSec);
// v1.0^
long longsec = (time_till / 1000) % 60;
long longmin = (time_till / (1000 * 60)) % 60;
long longhours = (time_till / (1000 * 60 * 60)) % 24;
showHours = (int) longhours;
showMin = (int) longmin;
showSec = (int) longsec;
showTime = String.format("%02d", showHours) + ":" + String.format("%02d", showMin) + ":" + String.format("%02d", showSec);
}
TextView lastTime = findViewById(R.id.textView4);
I want to update a TextView content every second and show a notification, but the TextView update and the notification show only when open the app, so
How can I update the TextView and show notification every one second in background?
You can user Timer and TimerTask to for recurring tasks. Don't forget to call timer.cancel() at end of the program.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//Call your method
LoadCurrentTime()
}
},0, 2000);

Android CountDown Timer : Add Hour

Add Hours in Count Down Timer , i have only minutes then how to format it
private void updateCountDownText() {
int hours = (int) (mTimeLeftInMillis / 1000) / 36000;
int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, seconds);
mTextViewCountDown.setText(timeLeftFormatted);
}
I'd recommend to use TimeUnit instead of manually converting time.
Try this:
int hours = TimeUnit.MILLISECONDS.toHours(mTimeLeftInMillis);
int minutes = TimeUnit.MILLISECONDS.toMinutes(mTimeLeftInMillis) % TimeUnit.HOURS.toMinutes(1);
int seconds = TimeUnit.MILLISECONDS.toSeconds(mTimeLeftInMillis) % TimeUnit.MINUTES.toSeconds(1);
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, seconds);
mTextViewCountDown.setText(timeLeftFormatted);

difference between countdown timer time with actual time in Android?

I have one countdown timer in my activity.
In which I have converted Mins into Millisecond.
Based on that Millisecond, I have managed to counter HH: mm: ss using CountDownTimer.
So, I want a difference between main time and remaining time.
For example, My main time is 00:10:00 and when I stop counter suppose my remaining time is 00:07:30. means I spend 2:30 seconds
An expected result I want is 150seconds.
Example Code:
public class MainActivity extends AppCompatActivity {
int duration;
TextView textView;
ProgressBar progressbar;
Button btn_stop, btn_resume;
CountDownTimer counter;
int i = 1;
int remainingDuration;
int countDownInterval = 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.tvSampleText);
progressbar = (ProgressBar) findViewById(R.id.progressbar);
btn_stop = (Button) findViewById(R.id.btn_stop);
btn_resume = (Button) findViewById(R.id.btn_resume);
// duration=81200000; //6 hours
duration = (int) TimeUnit.MINUTES.toMillis(1);
counter = new MyCount(duration, countDownInterval);
counter.start();
btn_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counter.cancel();
}
});
btn_resume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counter = new MyCount(remainingDuration, countDownInterval);
counter.start();
}
});
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
textView.setText("00:00:00");
}
#Override
public void onTick(long millisUntilFinished) {
i++;
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long elapsedHours = millisUntilFinished / hoursInMilli;
millisUntilFinished = millisUntilFinished % hoursInMilli;
long elapsedMinutes = millisUntilFinished / minutesInMilli;
millisUntilFinished = millisUntilFinished % minutesInMilli;
long elapsedSeconds = millisUntilFinished / secondsInMilli;
String yy = String.format("%02d:%02d:%02d", elapsedHours, elapsedMinutes, elapsedSeconds);
textView.setText(yy);
progressbar.setProgress((int) i * 100 / (duration / (int) secondsInMilli));
remainingDuration = (int) millisUntilFinished;
}
}
}
First convert the minutes duration into seconds
long secs = minutes * 60; 10 * 60 = 600
and inside on tick, you get the remaining time in milliseconds so keep the value as global reference and convert it into seconds as
long mMillisUntilFinished;
void onTick (long millisUntilFinished){
// mMillisUntilFinished = 450000
mMillisUntilFinished = millisUntilFinished;
}
then when you press stop then get the renaming time difference as
long diffSeconds = secs - (mMillisUntilFinished / 1000)
// 600 - (450000 /1000)
// 600 - 450
// 150
update: As suggested, calculate the seconds for both duration and left time then subtract them to get the result.
Use long instead of int casting
#Override
public void onTick(long millisUntilFinished) {
i++;
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long tempMili = millisUntilFinished;
long elapsedHours = tempMili / hoursInMilli;
tempMili = tempMili % hoursInMilli;
long elapsedMinutes = tempMili / minutesInMilli;
tempMili = tempMili % minutesInMilli;
long elapsedSeconds = tempMili / secondsInMilli;
String yy = String.format("%02d:%02d:%02d", elapsedHours, elapsedMinutes, elapsedSeconds);
textView.setText(yy);
progressbar.setProgress((int) i * 100 / (duration / (int) secondsInMilli));
remainingDuration = (duration/ 1000) - (millisUntilFinished/1000);
}

Timer adds a certain TableRow multiple times

I have a basic Timer in my app:
TextView timerTextView = (TextView) findViewById(R.id.timer);
long startTime = 0;
Handler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000) * 1;
int minutes = seconds / 60;
seconds = seconds % 60;
timerTextView.setText(String.format("%02d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
if (minutes == 45 && seconds == 0) {
addHeader("2nd Half");
}
}
};
addHeader() method:
private void addHeader(String header) {
TableLayout table = (TableLayout) findViewById(R.id.myTable);
TableRow tr = new TableRow(this);
tr.setLayoutParams(...);
TextView textView = new TextView(this);
textView.setLayoutParams(..);
textView.setText(header);
// more code
tr.addView(textView);
table.addView(tr);
}
onCreate():
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startTimer();
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
}
When my timer reaches 45:00 a new row is added to my TableLayout multiple times. I've created an alternative solution but I'd like to know what I'm missing.
if (!isAdded) {
addHeader("2nd Half");
isAdded = true;
}
A good way to check what is going on is to log every time the Handler is run and every time addHeader fires
e.g:
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000) * 1;
int minutes = seconds / 60;
seconds = seconds % 60;
millis = millis % 1000;
timerTextView.setText(String.format("%02d:%02d", minutes, seconds));
Log.d("MainActivity", String.format(Locale.ENGLISH,"Checking time: %02d:%02d:%03d" , minutes, seconds, millis));
timerHandler.postDelayed(this, 500);
if (minutes == 45 && seconds == 0) {
Log.d("MainActivity", String.format(Locale.ENGLISH,"2nd Half: %02d:%02d:%03d" , minutes, seconds, millis));
addHeader("2nd Half");
}
}
Doing this you will see that addHeader is called twice. This is because every 500ms your Handler is running, checking the difference between the current time and start time, in minutes and seconds (ignoring ms). To fix the issue try changing
timerHandler.postDelayed(this, 500);
to
timerHandler.postDelayed(this, 1000);

Getting millisecond format

I am trying to get this string to return Minute:Second:Millisecond for my MediaPlayer. I have found this code, but can't figure out how to make the Milliseconds work and put it at 2 decimal places. I'm sure its simple to the right person!
private String getTimeString(long millis) {
StringBuffer buf = new StringBuffer();
int hours = (int) (millis / (1000*60*60));
int minutes = (int) (( millis % (1000*60*60) ) / (1000*60));
int seconds = (int) (( ( millis % (1000*60*60) ) % (1000*60) ) / 1000);
buf
.append(String.format("%02d", hours))
.append(":")
.append(String.format("%02d", minutes))
.append(":")
.append(String.format("%02d", seconds));
return buf.toString();
}
Thanks always guys
There are 1000 milliseconds in one second, i.e. you'd need 3 decimal places for the milliseconds:
/** return time in format 1:23.456 */
private String getTimeString(long millis) {
int minutes = (int) (millis / (1000 * 60));
int seconds = (int) ((millis / 1000) % 60);
int milliseconds = (int) (millis % 1000);
String.format("%d:%02d.%03d", minutes, seconds, milliseconds);
}
If you absolutely want 2 digits for milliseconds, you actually get 1/100 seconds and not milliseconds:
/** return time in format 1:23.45 */
private String getTimeString(long millis) {
int minutes = (int) (millis / (1000 * 60));
int seconds = (int) ((millis / 1000) % 60);
int seconds100 = (int) ((millis / 10) % 100);
String.format("%d:%02d.%02d", minutes, seconds, seconds100);
}
However, a common display format for media players is to use one digit for 10ths of seconds:
/** return time in format 1:23.4 */
private String getTimeString(long millis) {
int minutes = (int) (millis / (1000 * 60));
int seconds = (int) ((millis / 1000) % 60);
int seconds10 = (int) ((millis / 100) % 10);
String.format("%d:%02d.%d", minutes, seconds, seconds10);
}
If you want to put the milliseconds at two decimal places, keep in mind that you will only be able to show increments of 10ms; 1ms = 0.001s, three decimal places. But regardless, the code you are looking for is:
int rem_milliseconds = (int)(millis % 1000); // Remaining ms after last second
...
.append(String.format("%02d", rem_milliseconds));
I left it at 2 decimal places.
Try this:
private String getTimeString(long millis) {
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
millis -= TimeUnit.MINUTES.toMillis(minutes) + TimeUnit.SECONDS.toMillis(seconds);
return String.format("%d:%d:%d", minutes, seconds, millis);
}

Categories