[Q#17212848][A#17213258] How to know if now time is between two hours?
https://stackoverflow.com/q/17212848
I have a now time: And I have some hour constants, for example, 23 and 8 (it's 11pm or 23:00, 8am or 08:00). How I can know is now time between it's two hour constants? It need to run some code of program or not to run if now time is between in two hours, for example, do not run some code if its already evening and while it is not a morning. Here the image to better explain:
Some situations when silent mode does not fire:
Answer
https://stackoverflow.com/a/17213258
try this
APIzation
int from = 2300;
int to = 800;
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
int t = c.get(Calendar.HOUR_OF_DAY) * 100 + c.get(Calendar.MINUTE);
boolean isBetween = to > from && t >= from && t <= to || to < from && (t >= from || t <= to);
package com.stackoverflow.api;
import java.util.Calendar;
import java.util.Date;
public class Human17213258 {
public static boolean isTimeBetweenTwoHours(int from, int to) {
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
int t = c.get(Calendar.HOUR_OF_DAY) * 100 + c.get(Calendar.MINUTE);
return (
to > from && t >= from && t <= to || to < from && (t >= from || t <= to)
);
}
}
package com.stackoverflow.api;
import java.util.Calendar;
import java.util.Date;
/**
* How to know if now time is between two hours?
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/17213258">https://stackoverflow.com/a/17213258</a>
*/
public class APIzator17213258 {
public static boolean know(int from, int to) throws Exception {
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
int t = c.get(Calendar.HOUR_OF_DAY) * 100 + c.get(Calendar.MINUTE);
return (
to > from && t >= from && t <= to || to < from && (t >= from || t <= to)
);
}
}