Reputation: 9
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.
Upvotes: 0
Views: 101
Reputation: 649
To use java.time
in low Android versions easily, you can use
1. ThreeTenABP
Put this in your build.gradle
:
implementation 'com.jakewharton.threetenabp:threetenabp:1.4.1'
Then in your Application class:
@Override
public void onCreate() {
super.onCreate();
AndroidThreeTen.init(this);
}
That's all, now use java.time
normally.
2. Or, as their github README suggests, use the new desugaring library
Upvotes: 1
Reputation: 227
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();
}
}
Upvotes: 0
Reputation: 355
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
}
Upvotes: 0
Reputation: 6985
You could do something like this:
java.time
APILocalTime now = LocalTime.now(ZoneId.of("required timezone"));
if (now.getHour() >= 18) {
//do something
} else {
//do something else
}
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.
Upvotes: 3