Good morning, i would want to know how to do something like this in android.
if(6PM are already passed){
//do somethin
}else{
//somethin else
}
Thanks in advance.
CodePudding user response:
You could do something like this:
- Modern
java.time
API
LocalTime now = LocalTime.now(ZoneId.of("required timezone"));
if (now.getHour() >= 18) {
//do something
} else {
//do something else
}
- Legacy Calendar
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Rome"));
int hour = calendar.get(Calendar.HOUR_OF_DAY);
Keep in mind, using the legacy API is cumbersome, error prone and generally discouraged, it's just that bad. I would recommend to research how to do desugaring.
CodePudding user response:
Use this function, you can extend it with dates if you want after:
public static void checkTimings() {
String pattern = "HH:mm";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
Date date1 = sdf.parse(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) ":" Calendar.getInstance().get(Calendar.MINUTE));
Date date2 = sdf.parse("18:00");
if (date1.before(date2)){
//before 6pm
} else {
//after 6pm
}
} catch (ParseException e) {
e.printStackTrace();
}
}
CodePudding user response:
if other solutions didn't work for you. You can try this
import java.util.Calendar;
import java.util.Date;
Date currentTime = Calendar.getInstance().getTime();
if(currentTime.getHours() >= 18){
// Above 6pm
} else {
// Below 6pm
}