I want to get the current time and compare that with time range provided by me.
for example I want to set the greeting message of Good morning if the current time is between 6:00 AM to 11:59 AM
Here is some code of my android Application
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class MainActivity extends Activity implements View.OnClickListener {
protected Calendar firstBound;
protected Calendar secondBound;
protected static Calendar cal;
protected static String timeString = null;
protected static String greetString = null;
protected static DateFormat date;
Button greetButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get a reference to the greetButton on the UI
greetButton = (Button) findViewById(R.id.greetButton);
cal = Calendar.getInstance(TimeZone.getDefault());
Date currentLocalTime = cal.getTime();
date = new SimpleDateFormat("HH:mm");
timeString = date.format(currentLocalTime);
char h1 = timeString.charAt(0);
char h2 = timeString.charAt(1);
char m1 = timeString.charAt(3);
char m2 = timeString.charAt(4);
cal.set(Calendar.HOUR,Character.getNumericValue(h1) + Character.getNumericValue(h2));
cal.set(Calendar.MINUTE,Character.getNumericValue(m1) + Character.getNumericValue(m2));
// Set the onClickListener for the greetButton to be this class.
// This requires that the class implement the View.OnClickListener callback
// the onClick() method
greetButton.setOnClickListener(this);
}
And My On Click method is
public void onClick(View v) {
TextView textMessage = (TextView) findViewById(R.id.textMessage);
EditText editFriendName = (EditText) findViewById(R.id.editFriendName);
String friendName = editFriendName.getText().toString();
switch (v.getId()) {
case R.id.greetButton:
// set the string being displayed by the TextView to the greeting
if(cal.after(setFirstBoundLimits(14, 00)) && cal.before(setSecondBoundLimits(18, 00))){
Toast.makeText(MainActivity.this, timeString, Toast.LENGTH_LONG).show();
}
// message for the friend
//textMessage.setText(getString(R.string.greetstring) + friendName + "!");
break;
default:
break;
}
}
private Calendar setFirstBoundLimits(int hh, int mm){
firstBound = Calendar.getInstance();
firstBound.set(Calendar.HOUR, hh);
firstBound.set(Calendar.MINUTE, mm);
return firstBound;
}