Search code examples
javaandroidtimercountdown

Countdown Timer that is date and time specific


    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


Solution

  • 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