Last active
October 13, 2018 06:00
-
-
Save zeero0/9066246718932d74f81e7383534c5299 to your computer and use it in GitHub Desktop.
Sample code for count down timer.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String FORMAT = "dd/MM/yyyy"; | |
private CountDownTimer mTimer; | |
public void startTimer() { | |
SimpleDateFormat sdfNew = new SimpleDateFormat(FORMAT); | |
String date = sdfNew.format(new Date()); | |
String endingDate = ""; | |
if (isBefore(date, "12/10/2018")) { | |
endingDate = "12/10/2018"; | |
} else if (isBefore(date, "14/10/2018")) { | |
endingDate = "14/10/2018"; | |
} | |
mTimer = new CountDownTimer(getEndingMiliseconds(endingDate), 1000) { | |
public void onTick(long millisUntilFinished) { | |
int seconds = (int) (millisUntilFinished / 1000); | |
int hours = seconds / 3600; | |
int minutes = (seconds % 3600) / 60; | |
seconds = seconds % 60; | |
String hourss = String.format("%02d", hours); | |
String minutess = String.format("%02d", minutes); | |
String secondss = String.format("%02d", seconds); | |
Log.e("TIMER", "onTick: " + hourss + ":" + minutess + ":" + secondss); | |
} | |
public void onFinish() { | |
Log.e("TIMER", "Timer finished: "); | |
} | |
}.start(); | |
} | |
public long getEndingMiliseconds(String endingTime) { | |
try { | |
DateFormat df = new SimpleDateFormat(FORMAT); | |
Date date1 = new Date(); | |
Date date2 = df.parse(endingTime); | |
long diff = date2.getTime() - date1.getTime(); | |
return diff; | |
} catch (ParseException e) { | |
Log.e("TEST", "Exception", e); | |
} | |
return 0; | |
} | |
public boolean isBefore(String startDate, String endDate) { | |
try { | |
SimpleDateFormat df = new SimpleDateFormat(FORMAT); | |
Date dateStart = df.parse(startDate); | |
Date dateEnd = df.parse(endDate); | |
return dateStart.before(dateEnd); | |
} catch (Exception e) { | |
return false; | |
} | |
} | |
@Override | |
protected void onStop() { | |
super.onStop(); | |
if (mTimer != null) { | |
mTimer.cancel(); | |
} | |
} | |
@Override | |
protected void onPause() { | |
super.onPause(); | |
startTimer(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment