Reputation: 61
I want to get the current system time and compare with the two different timing example start time as 2:00:00AM and end as 6:00:00AM. if my current system time falls between these i have to execute my rest of the code and show the output in textview. i have this use this code for getting the current time i need help for using start and end time in if condition.
enter code here
TextView tvTime = (TextView)findViewById(R.id.textView1);
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss a");
Calendar c = Calendar.getInstance();
if (if (c.getTime() == 2:00:00 AM && < 6:00:00 AM) {
tvTime.setText(" " + timeFormat.format(c.getTime()));
}
Upvotes: 0
Views: 2323
Reputation: 211
Anyway, java have problem with Date and Time.
You should use Joda Time It's date and time library to replace JDK date handling
Download: http://mvnrepository.com/artifact/joda-time/joda-time/2.3
Upvotes: 0
Reputation: 16739
try before()
and after()
methods of Calender
public boolean isTimeWithinInterval(String lwrLimit, String uprLimit, String time){
// Time 1 in string - Lower limit
Date time_1 = new SimpleDateFormat("HH:mm:ss").parse(lwrLimit);
Calendar calendar_1 = Calendar.getInstance();
calendar_1.setTime(time_1);
// Time 2 in string - Upper limit
Date time_2 = new SimpleDateFormat("HH:mm:ss").parse(uprLimit);
Calendar calendar_2 = Calendar.getInstance();
calendar_2.setTime(time_2);
// Time 3 in String - to be checked
Date d = new SimpleDateFormat("HH:mm:ss").parse(time);
Calendar calendar_3 = Calendar.getInstance();
calendar_3.setTime(d);
Date x = calendar_3.getTime();
if (x.after(calendar_1.getTime()) && x.before(calendar_2.getTime())) {
//checkes whether the current time is between two times
Log.d(TAG,true+"");
return true;
}
return false;
}
Update :
boolean timeChk = isTimeWithinInterval(time1, time2, time3);
if(timeChk){
// Success code
tvTime.setText(" " + time3);
}
else{
// Failure code
}
Upvotes: 3
Reputation: 18253
You should really try to use Calendar
class that is WAY easier and that has that feature with Calendar.before(calendar).
Upvotes: 0